Mike Belyakov Mike Belyakov - 1 month ago 10
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) }
end


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

Is there any way to use this functionality without
eval
?

Thank you!

Answer

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) }
  end
end