Mike Belyakov Mike Belyakov - 1 year ago 85
Ruby Question

Ruby dynamic lambda with static method

I'm writing Rails concern, and need to run something like

class Baz < ActiveRecord::Base
@base = 'awesome'
has_many :comments, ->() { where(have_#{@_base} => true) }

but lambda will be executed in
context. I've made hack with
eval "has_many :comments, ->() { where(have_#{@_base} => true) }"

Is there any way to use this functionality without

Thank you!

Answer Source

You can achieve it with BasicObject#instance_exec (it allows you to pass argument to the block):

class Baz < ActiveRecord::Base 
  @base = 'awesome'
  instance_exec(@base) do |arg|
    has_many :comments, -> { where("have_#{arg}" => true) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download