logo
down
shadow

How does ruby on rails dynamically define `find_by_id`, `find_by_name` methods?


How does ruby on rails dynamically define `find_by_id`, `find_by_name` methods?

Content Index :

How does ruby on rails dynamically define `find_by_id`, `find_by_name` methods?
Tag : ruby-on-rails , By : Brian Drum
Date : November 24 2020, 05:44 AM

seems to work fine This is the power of meta programmation in Ruby, and more specifically the method_missing method: https://ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing
When you call a method on an instance of a Class that is not defined in that class, the method_missing catches it and you can handle it there.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How can I dynamically define Object methods inside Ruby modules?


Tag : ruby , By : Steve
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , In your first example, you try to use undefined variable 'logger', as you can see from error message. Try to use the logger feature this way:
ActiveRecord::Base.logger = Logger.new(STDOUT)

Ruby On Rails: CanCan with Devise error 'undefined method `find_by_name' for #<Role:0x304ad18>


Tag : mysql , By : user143729
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further find_by_name is an ActiveRecord class method. (See the Active Record Query Interface Guide) You are invoking it like an instance method.
Try changing this:
def role?(role)
    return !!self.role.find_by_name(role.to_s.camelize)
end
def role?(role_name)
    return self.role.present? && self.role.name == role_name.to_s
end

Define class methods dynamically in Rails


Tag : ruby-on-rails , By : Ben
Date : March 29 2020, 07:55 AM
With these it helps It is not completely clear to me what you want to achieve. If you want to call a method, you naturally have to define it first (as long as ActiveRecord does not handle this). You could do something like this:
class MyClass
  class << self
    def method_missing(m, *args, &block)  
      match = m.to_s.match(/find_by_school([0-9]+)_id/)
      if match
        match.captures.first
      else
        nil
      end
    end  
  end
end

puts MyClass.find_by_school1_id
puts MyClass.find_by_school2_id
puts MyClass.find_by_school22_id
puts MyClass.find_by_school_id
1
2
22
nil

Ruby / Rails meta programing, how to define instance and class methods dynamically?


Tag : ruby-on-rails , By : hellboy32
Date : March 29 2020, 07:55 AM
Any of those help The key here is to use class_eval to open up the class you are calling denormalizable_collection on.
A simplified example is:
class Foo
  def self.make_method(name)
    class_eval do |klass|
      klass.define_singleton_method(name) do
        name
      end 
    end
  end

  make_method(:hello)
end

irb(main):043:0> Foo.hello
=> :hello
module DenormalizableCollection
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def denormalizable_collection(*actions)
      actions.each do |action|
        generate_denormalized_methods(action)
        generate_instance_methods(action)
        generate_callbacks(action)
      end
    end
    private
    def generate_denormalized_methods(action)

      self.class_eval do |klass|
        # you should consider if these should be instance methods instead.
        # define News.most_popular
        define_singleton_method "#{action}" do
          collection = Redis.current.get(send("#{action}_key"))
          return [] unless collection.present?
          JSON.parse(collection).map { |h| DenormalizedHash.new(h) }
        end
        # define News.most_popular
        # define News.set_most_popular
        define_singleton_method "set_#{action}" do
          Redis.current.set(send("#{action}_key"), send("#{action}_data").to_json)
        end
        # define News.most_popular_data, which is a method that returns an array of hashes
        define_singleton_method "#{action}_data" do
          raise NotImplementedError, "#{action}_data is required"
        end
        # define News.most_popular_key, the index key to use inside of redis
        define_singleton_method "#{action}_key" do
          "#{name.underscore}_#{action}".to_sym
        end
      end
    end

    def generate_callbacks(action)
      self.class_eval do
        # Since callbacks call instance methods you have to pass a
        # block if you want to call a class method instead
        after_commit -> { self.class.send("set_#{action}") }
        after_destroy -> { self.class.send("set_#{action}") }
      end
    end

    def generate_instance_methods(action)
      class_eval do
        define_method :a_test_method do
          # ...
        end
      end
    end
  end
end

Find_by_id in Ruby on Rails


Tag : ruby-on-rails , By : user184415
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Rails 6 and Google Maps for Rails
  • Ruby .map hash values to key value pair in array
  • Rails Frontend, Backend, and API
  • How to make value attribute in the select option tag to have url's in rails
  • Can I apply methods to a model.where condition to get all object created in specific month?
  • With Capybara, how do you get assertions on transient elements to work?
  • Best way to combine results of two select statements without returning an array?
  • How add extra attribute in model object response in rails
  • How can I block file uploads in Rails?
  • how does has_many :through work with only two models?
  • validating attribute presence with condition
  • How to fix "Illegal Argument Exception" when creating an Elasticsearch index for a Rails model?
  • Rails / Ruby how to always show decimal precision
  • Problem accessing images uploaded to heroku thru RoR application
  • How do I create a new path/route in Ruby and then link to it?
  • Rails Migration To Add Index To The Difference Between 2 Columns
  • i am trying to show my posts title on show page but it shows this error again and again . i am beginner in rails
  • Syntax Error for Ruby on Rails "(" unexpected
  • Upgrading from Rails 4.2.1
  • Reset master to an empty state
  • Ruby .round() function rounding off the values, but storing the original value only in database
  • Is it possible to email users who are @mentioned in rails ActionText?
  • Skip Current Migrations but Apply Future Ones
  • How to handle data with two has_many associations
  • Show SQL ActiveRecord queries in rails console using SemanticLogger gem
  • Custom strategy for Omniauth
  • How to obtain constant memory usage when migrating a Rails application from mongoid (MongoDB) to ActiveRecord (Postgres)
  • how do i redirect to home page(root )when user signed out?
  • Ruby two strings in an IF condition
  • Nginx passenger integration mode always require Passengerfile.json file?
  • what class is returned after a delete action in rails
  • Convert an array of hash with symbols
  • How can i display a particular product?
  • Rails remove subarray from array
  • Ruby : How to record an object and reuse it for tests?
  • Rails multiple select on array attribute not working
  • How use local views built with gem devise in rails app?
  • Deploying Rails App on Digital Ocean and when running cap production deploy:initial I get back ---> 01 ArgumentError:
  • How do I seed data of a class which requires the user_id of the current user?
  • How to do an RSpec oneliner to test a :count change
  • Rails 5 left_outer_join with specific saved ID
  • Rails: devise_invitable not accepting variables
  • How to spy on a method called at class level on ActiveRecord model?
  • Azure AD authentication with Rails and devise
  • Avoiding n+1 has_many children should remember parent
  • Ruby/Rails How to parse datetime from russian string
  • How to remove substring that may appear within a string?
  • param is missing or the value is empty: But parameter IS there with a value
  • What is cost/benefit of object.models.find() vs Model.find() in Ruby on Rails (Mongoid)
  • User is getting session from other logged in user with Rails / Devise
  • How to run docker compose up for production environment
  • In Rails 5 where should I put my javascript_include_tag?
  • Rubocop -> Use a guard clause
  • How does assigns know where to look for the instance variable in integration tests?
  • Rails 5.2.3 converting all params datatype to string when testing using rspec
  • RegEx for client-side server in Ruby on Rails
  • Aws CostExplorer Api giving exception using ruby sdk
  • rails webpack compilation hangs in production at 78% [0] chunk asset optimization TerserPlugin
  • How to remove an object from the ActiveRecord::Relation object
  • Where does http protocol rests in rails framework?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com