Forum: Ruby Can I set a module context for a block?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
drjflam (Guest)
on 2005-12-05 17:19
(Received via mailing list)
I'd really like to be able to inject the 'include Bob' statement in the
create method of Bob:

module Bob
  def method_missing(name, *params)
    puts "missing: #{name}"
  end
  def self.create(name)
    yield if block_given?
    puts name
  end
end

Bob::create('hi') do
  include Bob
  ldstr
  ldc_i4_0
end

Is there a way that I can avoid include Bob in my block?

Thanks
-John
http://www.iunknown.com
neil (Guest)
on 2005-12-05 17:31
(Received via mailing list)
John L. wrote:
>   end
> end
>
> Bob::create('hi') do
>   include Bob
>   ldstr
>   ldc_i4_0
> end
>
> Is there a way that I can avoid include Bob in my block?

  def self.create(name)
    module_eval do
      yield
    end if block_given?
    puts name
  end

--
Neil S. - removed_email_address@domain.invalid

'A republic, if you can keep it.' -- Benjamin Franklin
bob.news (Guest)
on 2005-12-05 17:31
(Received via mailing list)
John L. wrote:
>   end
> end
>
> Bob::create('hi') do
>   include Bob
>   ldstr
>   ldc_i4_0
> end
>
> Is there a way that I can avoid include Bob in my block?

module Bob
  def method_missing(name, *params)
    puts "missing: #{name}"
  end
  def self.create(name,&b)
    obj = Object.new
    obj.extend Bob
    obj.instance_eval(&b)
    puts name
  end
end

Bob::create('hi') do
  ldstr
  ldc_i4_0
end

irb(main):001:0> module Bob
irb(main):002:1>   def method_missing(name, *params)
irb(main):003:2>     puts "missing: #{name}"
irb(main):004:2>   end
irb(main):005:1>   def self.create(name,&b)
irb(main):006:2>     obj = Object.new
irb(main):007:2>     obj.extend Bob
irb(main):008:2>     obj.instance_eval(&b)
irb(main):009:2>     puts name
irb(main):010:2>   end
irb(main):011:1> end
=> nil
irb(main):012:0>
irb(main):013:0* Bob::create('hi') do
irb(main):014:1*   ldstr
irb(main):015:1>   ldc_i4_0
irb(main):016:1> end
missing: ldstr
missing: ldc_i4_0
hi
=> nil

Kind regards

    robert
drjflam (Guest)
on 2005-12-05 17:35
(Received via mailing list)
Thanks, Robert! Your solution neatly solves my next problem, which was
how
to declare a private context for the evaluation of the method_missing
elements.

Cheers,
-John
http://www.iunknown.com


module Bob
neil (Guest)
on 2005-12-05 18:08
(Received via mailing list)
Neil S. wrote:
[something wrong]

Bah, never mind, I thought I'd removed the 'include Bob' when I tested,
but I hadn't, heh.

--
Neil S. - removed_email_address@domain.invalid

'A republic, if you can keep it.' -- Benjamin Franklin
This topic is locked and can not be replied to.