vendredi 29 mars 2019

how to set up tenant name for foldering images uploaded with mongoid paperclip

i am trying to create folders for each tenant in my application when uplaoding pictures. I use mongoid paperclip, but i do not use any tenantcy gem. i have models with tenant_id, a banch of model indicates tenant id. Each user has a tenant. This is the general explanation of my application.

Getting an error while trying to install bootstrap-sass-3.2.0.1

I am getting an error when trying to bundle install.

This is the error - Could not find bootstrap-sass-3.2.0.1 in any of the sources

jeudi 28 mars 2019

How to write RSpec test for the following code

I have the functionality of my code working correctly, but need to create an RSpec test that covers it. My code in movies_controller.rb:

def find_with_same_director
  @movie = Movie.find(params[:id])
  @movies, check_info = Movie.find_with_same_director(params[:id])
  if check_info
    flash[:notice] = "'#{@movie.title}' has no director info"
    redirect_to movies_path
  end
end

The find_with_same_director function in the model, movie.rb:

def self.find_with_same_director(id)
  movie = self.find(id)
  if !movie.director.blank?
    movies = self.where(:director => movie.director).where.not(:id => movie.id)
    return movies, false
  else
    return [], true
  end
end

I am trying to write tests that covers the click on the "Find With Same Director" link that calls the function, when the movie that was clicked has a director to show, and when it doesn't. I've written the following tests in movies_controller_spec.rb for each so far:

describe 'find_with_same_director' do
  it 'should call the find_with_same_director model method' do
    expect(Movie).to receive(:find_with_same_director).with(params[:id])
    get :find_with_same_director, id: movie.id
  end

  context 'movie has a director' do
    let!(:movie1) {FactoryGirl.create(:movie, :director => movie.director)}
    it do
      get :find_with_same_director, id: movie1.id
      expect(response).to redirect_to(movie_path(movie1.id))
    end
  end

  context 'movie has no director' do
    let!(:movie1) { FactoryGirl.create(:movie, :director => nil)}
    it "should redirect to root" do
      get :find_with_same_director, id: movie1.id
      expect(response).to redirect_to(root_url)
    end
  end
end

I have spent hours working on these tests and while they are "covering" the lines when i check the report, they return fails. This means I wrote them incorrectly. I want to modify these tests to accurately represent what my controller code is doing and I would really appreciate some help with that. If you're feeling down to it I would also appreciate if you gave advice on writing the rspec test code for the model movie.rb file as well.

MimeType definition not applied to outgoing file

I added the following line to mime_types.rb: Mime::Type.register "application/x-xpinstall", :xpi in order to associate the content-type "application/x-xpinstall" with a Firefox extension "xxx.xpi" (and I restarted the local server). However, when key in the URL or click a link to the file, nothing appears in the server log and the file is downloaded apparently as "application/octet-stream". Just in case, I also tried #register_alias, which also did not work.

mercredi 27 mars 2019

Phusion Passenger - How to run code after request has been sent to the client?

This is similar to Is there an easy way to run Garbage Collection outside of the request cycle in Passenger? , but the accepted answer is 7+ years old and recommends patching the internals of Phusion passenger itself -- not something that I'd like to do in a production environment.

Is there a better way to do this in the newer versions of Phusion Passenger? Use-cases:

  • Out of band garbage collection
  • Pushing request/response stats (like cache hit ratio, time taken to render views, etc) to a collectd daemon

mardi 26 mars 2019

Ruby week number calculation issue

When I use

Time.now.strftime('%Y%W')
Date.today.strftime('%Y%W')

It returns 201912 while it should be 201913 we are in week 13.

Any clue?

rspec failing with error "block (2 levels) in

I'm trying execute some ruby script which involves sending REST calls, but its failing on below error.

An error occurred in an `after(:context)` hook.
NoMethodError: undefined method `logout_curl' for nil:NilClass
occurred at /root/343/auto/G/lib/common/rhelp.rb:110:in `block (2 levels) in <top (required)>'

I have the code block below from rhelp.rb:110

require_relative 'rest_request'
require_relative 'curl_request'    
.
.
.
config.after :all do
    $debug = true
$rest_api.logout_curl
      $curl_request.logout
$root_curl_request.logout
end

And the logout procedure is as below

require_relative 'curl_request'
.
.
.
def logout_curl
@curl_request.logout
end

Please let me know on how to rectify this error. Please note vertical 3 dots means I have only posted snippets.

lundi 25 mars 2019

I changed the column name, now heroku db:migrate doesn't work because the column doesn't exist

I changed the name of my 'image_url' column in my 'visions' table to 'image'. However, now when I try the command heroku run rake db:migrate, I get the error: PG::UndefinedColumn: ERROR: column "image_url" does not exist

rails db:migrate works fine. However, heroku run rake db:migrate gives me the error.

this is my migration file for changing the column name:

  def change
    rename_column :visions, :image_url, :image
  end
end

My schema for that table:

    t.string "description"
    t.string "image"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["user_id"], name: "index_visions_on_user_id"
  end

Hyperstack and MaterialUI Drawer Toggling State is causing the drawer to open and close repeatedly

I am implementing a title bar and menu drawer using MaterialUI in a Hyperstack project. I have two components, a Header component, and a Menu component. The Menu component is the expandable Drawer. I am storing the state in the Header component and passing it and a handler to the Menu component to toggle the drawer state when the drawers close button is clicked. For some reason, the drawer is just toggling open and closed very rapidly and repeatedly.

The drawer was opening fine before I implemented the close button. I have tried moving the state up to the main app component and passing it all the way down, but it produces the same result. I tried setting a class function on the Header component and calling it from within the Menu component instead of passing in an event handler.

The Header component

class Header < HyperComponent
  before_mount do
    @drawer_open = false
  end

  def toggle_drawer
    mutate @drawer_open = !@drawer_open
  end

  render(DIV) do
    AppBar(position: 'static', class: 'appBar') do
      Toolbar do
        IconButton(class: 'menuButton', color: 'inherit', aria_label: 'Menu') do
          MenuIcon(class: 'icon')
        end
        .on(:click) do
          toggle_drawer
        end
        Typography(variant: 'h6', color: 'inherit', class: 'grow') { 'Admin Main' }
        Button(color: 'inherit', class: 'float-right') { 'Login' } # unless App.history != '/admin'
      end
    end
    Menu(open_drawer: @drawer_open, toggle_drawer: toggle_drawer)
  end
end

The Menu component

class Menu < HyperComponent
  param :open_drawer
  param :toggle_drawer

  def menu_items
    %w(Main Inventory Customers)
  end

  def is_open?
    @OpenDrawer
  end

  render(DIV) do
    Drawer(className: 'drawer, drawerPaper', variant: 'persistent', anchor: 'left', open: is_open?) do
      IconButton(className: 'drawerHeader') { ChevronLeftIcon() }
      .on(:click) { @ToggleDrawer }

      List do
        menu_items.each do |mi|
          ListItem(button: true, key: mi) { ListItemText(primary: mi) }
        end
      end
    end
  end
end

I expected for the drawer to open on the open button click and close when the close button is clicked, but it is just opening and closing very rapidly.

How should I include before do in minitest rails3.2?

What is the syntax for writing before do in minitest ?

I am trying to write a test case using minitest in rails3.2.

In development environment, we are loading this data using some background jobs. so, I have tried to do the same thing in test environment also. Before running my test suite, I have to run the task in background and generate vibrancy data and the same is being used in the test suite for asserting. but, it's throwing undefined method `before' for CommunityVibrancyTest:Class (NoMethodError)

   require 'test_helper'

   Class CommunityVibrancyTest < ActiveSupport::TestCase

     before :each do
       App::Queue.add(CommunityVibrancyWorker, communities(:private_community).id )
     end

     test 'to check whether the vibrancy of a private community is handliing share or not' do

       private_community = communities(:private_community)
       share = shares(:share_for_private_microblog)
       stat = share.object
       post_vibrancy = stat.aggregated_score_mblog.round(1)
       assert_equal post_vibrancy, private_community.community_vibrancies.last.post_vibrancy
     end
   end

test/unit/community_vibrancy_test.rb:24:in <class:CommunityVibrancyTest>': undefined methodbefore' for CommunityVibrancyTest:Class (NoMethodError) from test/unit/community_vibrancy_test.rb:4:in `'

Outer transaction rollback not working rails

I am trying to update few records in my database, but unlucky.

I want this manipulations to be atomic (using transaction). What i want is that I need to update few attributes in table 1 and few attributes in table 2.

If the update process fails in any of the table, i want all the changes that were made in both the tables to get rollbacked.

Below is my not working code:

    def make_settings(account,attributeToUpdate,attribute_type)
    A.transaction do
      B.transaction do
          if attribute_type == "ADVANCED"
          self.user.create_or_update_attribute(attributeToUpdate[0],attributeToUpdate[1].to_s)
          end
     if attribute_type == "BASIC"
        us = account.user.user_setting.reload
        us[attributeToUpdate[0]] = attributeToUpdate[1]
        us.save!
      end
    end
  end 
end

What is happening now:- If the attribute type is ADVANCED few attributes are updated successfully in table A. The flow then proceeds to update attributes in table B, but something goes wrong while doing that.

Now what i want is when the updation in table B fails, then the records that got added/updated in table A should also get deleted/updated back. But that is not happening.

Can anyone help ? Thanks

vendredi 22 mars 2019

Correct format for writing conditionals in ruby and then converting output into string using string interpolation inside HAML tag

I am fixing a bug in a ruby on rails open source project at the front end of the project. I am a newbie to ruby on rails, HAML etc. The following line of code is giving me a lot of trouble.

I am wondering what would be correct way to format this. Further, is there a way to write a helper function to turn the conditionals into a function call? Any help will be appreciated.

I have tried several formats but the devs want me to break up the if-else into several lines. I am unable to make that work.

%strong 
= "#{"producer " 
- if @enterprise.is_primary_producer
  = t('.producer_profile')
- else
  = t('.profile')
  }profile"


I expect the view to be rendered but instead I get syntax errors.

jeudi 21 mars 2019

Listing Articles with date attribute before/after the current date

I have an admin page on my site that usually lists all appointments that users have scheduled when I use @appointments.each. I'm trying to figure out how I can list all appointments with the date attribute after whatever day it currently is, and how I would list all appointments with dates before the current date. I've looked at a bunch of stackoverflow examples but anytime I change the query, none of the appointments show up anymore (like the one directly below). Heres my admin page:

<div align="center">
    <div class="col-md-6">
      <div class="card">
        <h5 class="card-header">All Currently Scheduled Appointments</h5>
        <div class="card-body">
          <%@appointments.where("date >= ?", Date.current) do | appt |%>
            <%="Appointment for #{appt.owner_email} on #{appt.date} in the #{appt.time}"%> <%= link_to 'Edit', edit_appointment_path(appt) %>
            </br>
          <%end%>
        </div>
      </div>
    </div>
  </div>

Heres my appointment table in the schema file, the date attribute stores them as "2019-03-21" for example.

  create_table "appointments", force: :cascade do |t|
    t.string "VIN"
    t.string "owner_email"
    t.string "date"
    t.string "time"
    t.string "reason"
    t.string "parts_needed"
    t.string "hours_needed"
    t.string "cost"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

lundi 18 mars 2019

undefined method `id' for "":String

I am trying to save has_one through rails form. I have a class

class Org
  has_one :org_name
  has_one :org_type, through: :org_name
end

and this is my form field for saving org

= f.select 'org_type', OrgType.order('name').collect { |t| [t.name, t.id] }, { include_blank: true }, class: 'data_field'

when I am saving record without selecting org_type it throws an error

NoMethodError - undefined method `id' for "":String:
(gem) activerecord-3.1.12/lib/active_record/associations/through_association.rb:47:in `block in construct_join_attributes'

at below line means during initialization. My org model already has this validation validates_associated :org_type

@org = Org.new(params[:org])

I am using rails 3.1.12. How can I validate has_one relation and throw a custom error message.

dimanche 17 mars 2019

How to use my little class from ruby on ruby on rails

I have wrote one little class on ruby, and i want to use she, on ruby on rails, for showing on each pages, date and hours on french, how to be good placed, she on for having on each views ? if possible to explain, whole procees ? Many thanks, Here is she..

# Petite classe pour récupérer le jour et l'heure en Français

class JourFrancais

def initialize()
    self.jourj
end
def jourj
    jours_ouvrables = {Lundi: 'monday', Mardi: 'tuesday', Mercredi: 'wednesday', Jeudi: 'thursday', Vendredi: 'friday', Samedi: 'saturday', Dimanche: 'sunday'}


    jours_ouvrables.each do |key, value|
        if Time.now.strftime("%A").downcase == value
        puts "Nous sommes le #{key} " + Time.now.strftime("%d/%m/%Y") + " et il est " + Time.now.strftime("%H:%M")

        end
    end
end end

thanks for your help..

vendredi 15 mars 2019

Problem with getting Rails ENV variable in yml file, it give float instead of whole string

I have an Environment variable in me env file that is

SOME_CLIENT_ID= 574536488180.574908975999

and I included this in my secrects.yml file like this

some_client_id: <%= ENV['SOME_CLIENT_ID'] %>

and when I'm getting this in my .rb and rails console with Rails.application.secrets.some_client_id this give me 574536488180.575 instead of 574536488180.574908975999 and ENV['SOME_CLIENT_ID'] Gives accurate value. Rails.application.secrets.some_client_id seems like it give me round of value but I needed as I entered orignal value.

how can I tackle this issue? please help me. thanks

jeudi 14 mars 2019

how to save a blob file using carrierwave in rails

So i have a requirement where i record a video and save it in the database, the recording of the video is working fine, only thing is it generates a blob file, then i use js to send the blob file to the server. This are my params

{"testqwe"=>{"attr"=>"blob:http://localhost:3000/6f12f123-b1d0-7bfc-6b15-d3b54341946"}, "controller"=>"myControler", "action"=>"test"}

i have an uploader in place , but it does not save anything.

so how can i save this using carierwave to my database?

here is my javascript

mediaRecorder.onstop = (ev) ->
        blob = new Blob(chunks, 'type': 'video/mp4;')
        chunks = []
        videoURL = window.URL.createObjectURL(blob)
        vidSave.src = videoURL
        $.ajax
          type: 'POST'
          content_type: "video/webm"
          url: '/test'
          enctype: "multipart/form-data"
          data: testqwe: attr: videoURL
        return

Are both rails query return the same record?

Resume.joins(:languages, :publications).where('first_name LIKE ? OR last_name LIKE ? OR email LIKE ?', "%abcd%", "%abcd%", "%abcd%")


Resume.where('first_name LIKE ? OR last_name LIKE ? OR email LIKE ?', "%abcd%", "%abcd%", "%abcd%")

I am using the Rails 3.2

NoMethodError when trying to view post as another user

Users can leave reviews for a post in my rails app, if I leave a review on a post as the current_user and view the review on the post-show page I don't get any errors, but I get "NoMethodError undefined method `username' for nil:NilClass" if I'm signed in as another user and try to see the other review left on that post.

<p> Posted by <%= review.user.username %> </p>
<p><%= review.comment %></p>
</div>
</div>

<% if user_signed_in? %>

<% if review.user_id == current_user.id %>

<%= link_to "Edit", edit_post_review_path(review.post, review) %>
<%= link_to "Delete", post_review_path(review.post, review),method: :delete, data: { confirm: "Are you sure you want to permanently delete your review?"} %>

mercredi 13 mars 2019

Can not return desired result from database

I am making a simple query in Rails but I can not seem to get the desired result, I god:

<%= User.select(id: @list.user_id).pluck(:username) %>

and it is working fine, but I get

["User1"] instead of User1

I tried .to_s but it did not work, thank you in advance!

mardi 12 mars 2019

Open a folder with index.html outside of Public Folder [Rails]

So guys, I just create my swagger documentation by manually type it on swagger editor and then attach it in swagger-UI. I can call my documentation well by place it on public/documentation (where the documentation folder include my swagger.json file and swagger-ui in it). Then I call it by using localhost:3000/documentation/ and here's the result. localhost:3000/documentation

So, the point is, how do I make it protected? I mean it's not an for public consumption. I've been thinking to move it outside public folder then call it using controller. But none of them working.

dimanche 10 mars 2019

ActiveRecord: is it possible do a join with a scope

Here is my original problem. I have two models as below.

class Author < ActiveRecord::Base
  has_many :books
end

and

class Book < ActiveRecord::Base
  belongs_to :author

  scope :available, ->{ where(available: true) }
end

I would like to left join ActiveRecord to Book's scope available. Following is the query I would like to execute on DB. Is it possible to do this ?

Select authors.* , count(books.*) as books_count 
From authors left outer join books on books.author_id = authors.id 
and books.available = true 
group by (authors.id) order by books_count;

I have tried following method

 Author.joins("LEFT OUTER JOIN authors on books.author_id = authors.id")
.merge(Book.available)
.select("authors.* , count(books.*) as books_count")
.group("authors.id").order("books_count")

But that result in following query.

Select authors.* , count(books.*) as books_count 
From authors left outer join books on books.author_id = authors.id 
where books.available = true 
group by (authors.id) order by books_count;

So it remove all the authors who are not having a book.

Important: My AR version doesn't have left_outer_joins method

vendredi 8 mars 2019

How to obtain basename in ruby from the given file path in unix or windows format?

I need to parse a basename in ruby a from file path which I get as input. Unix format works fine.

File.basename("/tmp/text.txt")

return "text.txt".
However, when I get input in windows format:

File.basename("C:\Users\john\note.txt")

"C:Usersjohn\note.txt" is the output.

Is there some nice solution in ruby/rails?

Is save method mandatory in rails?

Model.find(ids).each { |model| model.is_active = false } unless ids.empty?

Here, is model.save method necessary or not ? Because without that also, it's working.

mercredi 6 mars 2019

How to create Header and footer using Axlsx Gem in Rails?

I am trying to create the header and footer with the below code in the rails. But it is not creating the header and footer in the Excel file. Where I did wrong?

     xlsx_package = Axlsx::Package.new
        wb = xlsx_package.workbook
        header_footer = {:different_first => false, odd_header:'&C&14 &B&UHeader Text', odd_footer:'&L&11&BPage &P &C&11Footer Text &R&11&ILast updated:&D'}
        wb.add_worksheet(name: "header footer", :header_footer => header_footer) do |sheet|
             sheet.add_row ["First Column", "Second", "Third"]
             sheet.add_row [1, 2, 3]
       end

Delete has_one id associate with has_many primary key?

I have 2 models :

class Agency < ApplicationRecord

has_one :branding

end


class Branding < ApplicationRecord

has_many :agencies

end

when I was destroying any branding, it still keeps its key with the Agency, where I made a field "branding_id".

I want something which nullifies it when any branding got to destroy in the process. It automatically updates the agency branding_id to null.

lundi 4 mars 2019

How to track users in Rails using Google Analytics

I am using the following google analytics code to track users in my Ruby on Rails 4 app

    // ga('create', 'UA-1234567-1', 'auto');
    ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.id %> });
    // ga('set', '&uid', <%= current_user.id %>); // Set the user ID using signed-in user_id.
    ga('send', 'pageview');

but I am getting the error

undefined method `id' for nil:NilClass

for the line

ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.id %> });

I am following this thread How do I set USER_ID in Google Universal Analytics tracking code in Rails? and official doc https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id but not sure what is going wrong as it is almost same code.

Do I need to restart Server : Ruby on Rails

Do I need to restart Server when i change the database host in the database.yml in Ruby on Rails. Database is Postgres.

I haven't worked on Ruby On Rails, and the reason i am asking this is because its a production server.

Not able to print html format barcode in rails app

I'm having some issue using Barby gem. It happens when I try to print the webpage. The barcode is showing on the page, but if I try to print, was not on the print preview

samedi 2 mars 2019

How to snooze wavefront alerts via Ruby code?

I am new to wavefront, I know how to snooze wavefront alert via UI. But I have a ruby script, which gets triggered in regular intervals and performs certain functionality and while (before) doing so, it has to snooze the wavefront alerts.

Any help is greatly appreciated. Thanks in advance!

vendredi 1 mars 2019

Implementing omniauth strategy for authorization code grant

I'm attempting to use Omniauth to implement an authorization code grant-type through Okta. I've implemented a strategy that is nearly identical to that in the okta omniauth gem. I've added the necessary code to the devise initializer and it easily retrieves the authorization code and grant type form the authorization endpoint. However, when it returns the parameters to the redirect_uri, I don't understand how to get the strategy to initiate the callback_phase method which is necessary to exchange the code for an access token with the token endpoint. As a result, the auth hash is not created so the User.from_omniauth call in my controller throws an error.

Question: How do I deliver the access code to my strategy to retrieve the access token?

Any help would be greatly appreciated.

Strategy: require 'omniauth' require 'net/http'

# frozen_string_literal: true

require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Moto < OmniAuth::Strategies::OAuth2

      ORG           = AUTH['oauth2']['moto']['OKTA_ORG']    || 'your-org'
      DOMAIN        = AUTH['oauth2']['moto']['OKTA_DOMAIN'] || "https://#{ORG}.okta.com"
      BASE_URL      = DOMAIN
      DEFAULT_SCOPE = %[openid profile email].freeze

      option :name, 'moto'

      option :skip_jwt, false
      option :jwt_leeway, 60
      option :redirect_uri, AUTH['oauth2']['moto']['redirect']

      option :client_options, {
        site:          BASE_URL,
        authorize_url: "#{BASE_URL}/oauth2/v1/authorize",
        token_url:     "#{BASE_URL}/oauth2/v1/token",
        response_type: 'authorization_code'
      }

      option :scope, DEFAULT_SCOPE

      uid { raw_info['sub'] }

      info do
        {
          name:       raw_info['name'],
          email:      raw_info['email'],
          first_name: raw_info['given_name'],
          last_name:  raw_info['family_name'],
          image:      raw_info['picture']
        }
      end

      extra do
        hash = {}
        hash[:raw_info] = raw_info unless skip_info?
        hash[:id_token] = access_token.token
        if !options[:skip_jwt] && !access_token.token.nil?
          hash[:id_info] = validated_token(access_token.token)
        end
        hash
      end

      alias :oauth2_access_token :access_token

      def access_token
        puts "in access token"
        ::OAuth2::AccessToken.new(client, oauth2_access_token.token, {
          :refresh_token => oauth2_access_token.refresh_token,
          :expires_in    => oauth2_access_token.expires_in,
          :expires_at    => oauth2_access_token.expires_at
        })
      end

      def raw_info
        @_raw_info ||= access_token.get('/oauth2/v1/userinfo').parsed || {}
      rescue ::Errno::ETIMEDOUT
        raise ::Timeout::Error
      end

      def request_phase
        puts "In request phase"
        super
      end

      def callback_phase
        puts "in callback phase"
        build_access_token
        super
      end

      def callback_url
        options[:redirect_uri] || (full_host + script_name + callback_path)
      end

      def validated_token(token)
        JWT.decode(token,
                   nil,
                   false,
                   verify_iss:        true,
                   iss:               BASE_URL,
                   verify_aud:        true,
                   aud:               BASE_URL,
                   verify_sub:        true,
                   verify_expiration: true,
                   verify_not_before: true,
                   verify_iat:        true,
                   verify_jti:        false,
                   leeway:            options[:jwt_leeway]
                   ).first
      end
    end
  end
end

controller callback

class OmniauthController < Devise::OmniauthCallbacksController
def moto_callback
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    puts "Request env #{env['omniauth.auth']}"
    logger.debug "Request env #{env['omniauth.auth']}"
    @user = User.from_omniauth(request.env["omniauth.auth"])
    print(@user)
    if @user.save
        session[:oktastate] = request.env["omniauth.auth"]
        print(@user.oauth_permissions(session[:oktastate]))
    else
        print(@user.errors.full_messages)
    end
    if @user.persisted?
        redirect_to "/users"
    end
end
end

initializer/devise.rb

config.omniauth(:moto, AUTH['oauth2']['moto']['OKTA_CLIENT_ID'], AUTH['oauth2']['moto']['OKTA_CLIENT_SECRET'], :scope => 'openid profile email', :fields => ['profile', 'email'], :strategy_class => OmniAuth::Strategies::Moto)