Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to define class methods for models w/ Metaprogramming...


  • Please log in to reply
1 reply to this topic

#1 sonnychee

sonnychee

    Passenger

  • Members
  • 1 posts

Posted 16 November 2016 - 10:11 PM

Hey Guys,

 

I used the following snippet to define some class methods with no success....

 

  Status.all.each {|c|
     define_method("self.#{c.name.downcase}(params)") do |o|
       find_by(customer_id: o[:customer_id], status_id: "#{c.id}")
     end
  }

 

No compile error but the class methods were not defined.  Anyone have any idea why?



#2 Christoph

Christoph

    Passenger

  • Members
  • 1 posts

Posted 03 December 2016 - 11:31 AM

Hej sonnychee,

 

You wanna use Object#define_singleton_method, like so:

Status.all.each do|c|
  define_singleton_method(c.name.downcase) do |params|
    find_by(customer_id: params[:customer_id], status_id: c.id)
  end
end

Just be careful with the Status.all, that will potentially bite you and lead to all kind of weird situations, if you're DB isn't initialized yet.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users