I create a dynamic class using the Class.new method. But sometimes I call the method with a parameter to create an inherited class - sometimes without.
Option 1:
newclass = Class.new do
...
end
Option 2:
newClass = Class.new(p) do
...
end
The body of the new class is identical. But I cannot call Class.new(p) with undefined p. So I have to create an if statement and then either call Class.new with parameter or without which means I have the duplicate the code for creating the class which is not ideal since every change in my code I have to make twice. Any way how I can get around this?
You can just abstract the Class.new call and leave the block in one place. Something like this:
def create_me_a_class(superklass = Object, &block)
Class.new(superklass, &block)
end
newclass = create_me_a_class(p) do
def my_method
# whatever
end
end
Related
I'm trying to wrap all instance methods of TestClass to perform code before and after an instance method is called. So far, this code is working:
module Wrapper
def wrap(*methods)
prependable_module = Module.new do
methods.each do |m|
define_method(m) do |*args, &block|
p 1
super(*args, &block)
p 3
end
end
end
prepend prependable_module
end
end
class TestClass
extend Wrapper
wrap :instance_method1
def instance_method1
p 2
end
end
TestClass.new.instance_method1 # => 1, 2, 3
I can call wrap with all method names as arguments. If I try to wrap all methods without listing them individually, I need to call it using instance_methods(false) at the bottom of the class definition.
class TestClass
extend Wrapper
def instance_method1
p 2
end
wrap(*instance_methods(false))
end
In Rails, all callback methods like before_action or after_create are usually called on top of the class definition. My goal is to call wrap on top of the class definition as well (without listing all methods individually). In this case, I can't call instance_methods(false) on top of the class definition, because at this point no method has been defined.
Thanks for your help!
Update
Thanks to Kimmo Lehto's approach I can wrap every instance method using the method_added hook. I don't want to prepend a new module for every defined method, so I add all overridden methods to the same module.
module Wrapper
def method_added(method_name)
tmp_module = find_or_initialize_module
return if tmp_module.instance_methods(false).include?(method_name)
tmp_module.define_method(method_name) do |*args, &block|
p 1
super(*args, &block)
p 3
end
end
def find_or_initialize_module
module_name = "#{name}Wrapper"
module_idx = ancestors.map(&:to_s).index(module_name)
unless module_idx
prepend Object.const_set(module_name, Module.new)
return find_or_initialize_module
end
ancestors[module_idx]
end
end
class TestClass
extend Wrapper
def instance_method1
p 2
end
end
tc = TestClass.new
tc.instance_method1 # => 1, 2, 3
You could use the Module#method_added hook to automatically wrap any methods that are added.
You will need some magic to not get a stack overflow from an infinite loop.
Another option is to use TracePoint to trigger the wrapping once the class has been defined. You can use the Module#extended to set up the tracepoint. Something like:
module Finalizer
def self.extended(obj)
TracePoint.trace(:end) do |t|
if obj == t.self
obj.finalize
t.disable
end
end
end
def finalize
wrap(*instance_methods(false))
end
end
Classes are usually not exactly "closed" unless you explicitly .freeze them so it's a bit of a hacky solution and will not trigger if methods are added afterwards. method_added is probably your best bet.
This part of code dynamically creates several classes:
(1..MAX_ACT).each do |act_id|
klass = Class.new(ActB) do
def initialize(trg)
super(trg, act_id)
end
end
Object.const_set("Act#{act_id}", klass)
end
In this case, the common base class (ActB) has a constructor with two parameters, while the child classes have a constructor with one parameter.
Running this code works well, but when I later try to instantiate one of these classes, for example
Act3.new(4)
I get the error message
NameError: undefined local variable or method `act_id' for #<Act3:0x00000006008b7990>
The error message must refer to the line
super(trg, act_id)
because this is the only place in my program where I am using this variable. However, this variable is defined a few lines above, when it says
(1..MAX_ACT).each do |act_id|
I had expected, that the do...end block creates a closure for the constructor, where act_id is bound. However, this doesn't seem to be the case.
Why does my example not work? How do I have to do it correctly?
def (and class and module) creates a fresh local scope, which doesn't inherit any locals from outside.
So you're right that the Class.new do .. end creates a closure... but the inner def doesn't share it.
If you need standard block behaviour, you can use define_method instead:
(1..MAX_ACT).each do |act_id|
klass = Class.new(ActB) do
define_method :initialize do |trg|
super(trg, act_id)
end
end
Object.const_set("Act#{act_id}", klass)
end
Just out of curiosity, there is a hack, allowing to fool scoping and still use def initialize :)
class ActB
def initialize(trg, act_id)
puts "ActID: #{act_id}"
end
end
(1..MAX_ACT).each do |act_id|
klass = Class.new(ActB) do
#act_id = act_id
def initialize(trg)
super(trg, self.class.instance_variable_get(:#act_id))
end
end
Object.const_set("Act#{act_id}", klass)
end
Act1.new :foo
#⇒ ActID: 1
Act2.new :foo
#⇒ ActID: 2
The problem here is that the block passed to Class.new is executed in the context of that class. In the context of that class, act_id is not defined. So, to fix this, you can move the method definition outside of the class initialization, like so:
(1..MAX_ACT).each do |act_id|
klass = Class.new(ActB)
klass.define_method(:initialize) do |trg|
super(trg, act_id)
end
Object.const_set("Act#{act_id}", klass)
end
Is there a way to bind an existing method to an existing instance of an object if both the method and the instance are passed as symbols into a method that does that if the instance is not a symbol?
For example:
def some_method
#do something
end
some_instance = Klass.new(something)
def method_that_binds(:some_method, to: :some_instance)
#how do I do that?
end
Your requirements are a little unusual, but it is possible to do this mostly as you say:
class Person; end
harry = Person.new
barry = Person.new
def test
puts 'It works!'
end
define_method :method_that_binds do |a_method, to|
eval(to[:to].to_s).singleton_class.send(:define_method, a_method, &Object.new.method(a_method))
end
method_that_binds :test, to: :harry
harry.test
# It works! will be sent to STDOUT
barry.test
# undefined method 'test'
This doesn't actually use a named parameter, but accepts a hash with a to key, but you can see you can call it in the way you want. It also assumes that the methods you are defining are defined globally on Object.
The API you want doesn't easily work, because you have to know from which scope you want to access the local variable. It's not quite clear to me why you want to pass the name of the local variable instead of passing the content of the local variable … after all, the local variable is present at the call site.
Anyway, if you pass in the scope in addition to the name, this can be accomplished rather easily:
def some_method(*args)
puts args
puts "I can access some_instance's ivar: ##private_instance_var"
end
class Foo; def initialize; #private_instance_var = :foo end end
some_instance = Foo.new
def method_that_binds(meth, to:, within:, with: [])
self.class.instance_method(meth).bind(within.local_variable_get(to)).(*with)
end
method_that_binds(:some_method, to: :some_instance, within: binding, with: ['arg1', 'arg2'])
# arg1
# arg2
# I can access some_instance's ivar: foo
As you can see, I also added a way to pass arguments to the method. Without that extension, it becomes even simpler:
def method_that_binds(meth, to:, within:)
self.class.instance_method(meth).bind(within.local_variable_get(to)).()
end
But you have to pass the scope (Binding) into the method.
If you'd like to add a method just to some_instance i.e. it's not available on other instances of Klass then this can be done using define_singleton_method (documentation here.)
some_instance.define_singleton_method(:some_method, method(:some_method))
Here the first use of the symbol :some_method is the name you'd like the method to have on some_instance and the second use as a parameter to method is creating a Method object from your existing method.
If you'd like to use the same name as the existing method you could wrap this in your own method like:
def add_method(obj, name)
obj.define_singleton_method(name, method(name))
end
Let's say we have a class A with a method a and a local variable c.
class A
def a; 10 end
end
c = '5'
And we want to add the method A#a to c.
This is how it can be done
c.singleton_class.send :define_method, :b, &A.new.method(:a)
p c.b # => 10
Explanations.
One way to add a method to an object instance and not to its class is to define it in its singleton class (which every ruby object has).
We can get the c's singleton class by calling the corresponding method c.signleton_class.
Next we need to dynamically define a method in its class and this can usually be accomplished by using the define_method which takes a method name as its first argument (in our case :b) and a block. Now, converting the method into a block might look a bit tricky but the idea is relatively simple: we first transform the method into a Method instance by calling the Object#method and then by putting the & before A.new.method(:a) we tell the interpreter to call the to_proc method on our object (as our returned object is an instance of the Method, the Method#to_proc will be called) and after that the returned proc will be translated into a block that the define_method expects as its second argument.
I am trying to create a macro "has_accessor_for", that accepts a symbol which is used as a parameter for an internal object that it uses (the Accessorizer object). The problem I am having is, when multiple modules do the has_accessors_for, the parameter (scope) ends up being stuck on the last value it was assigned to.
I added a puts prior to the define_method, which shows that it's scope1, and then scope2... But inside the define_method, it's scope2 always. I am looking for a way to basically encapsulate that variable, so that when it the first module calls has_accessor_for, anytime my_wut is called, it will be bound to scope1... and anytime my_bleah is called, it will be bound to scope2. But as I said, right now, both my_bleah and my_wut are bound to scope2-- If I change the order of the includes in MyModel, then they will both be bound to scope1.
class Accessorizer
def initialize(record, scope)
#record = record
#scope = scope
end
def value_for(key)
#record.send key
end
end
module Magic
def has_accessors_for(scope)
accessors = {}
puts "initial: #{scope}"
define_method :get_value_for do |key|
puts "inside method #{scope}"
accessor.value_for key
end
define_method :accessor do
accessors[:scope] ||= Accessorizer.new(self, scope)
end
end
end
module SomeAccessor
extend Magic
has_accessors_for :scope1
def my_wut
get_value_for :wut
end
end
module SomeOtherAccessor
extend Magic
has_accessors_for :scope2
def my_bleah
get_value_for :bleah
end
end
class MyModel
include SomeAccessor
include SomeOtherAccessor
attr_accessor :wut, :bleah
end
m = MyModel.new
m.wut = 'wut'
m.bleah = 'bleah'
m.my_bleah
m.my_wut
output:
initial: scope1
initial: scope2
inside method scope2
inside method scope2
Short answer: the problem is not with the closures.
Long answer:
define_method :get_value_for do |key|
puts "inside method #{scope}"
accessor.value_for key
end
On a given class there can only be one method called get_value_for - the second definition will overwrite the first.
It doesn't matter so much because you're call accessor in both cases, however that method suffers from the same problem - you define it twice and so the second definition overwrites the first and you end up with only one Accessorizer object.
I think you'll need to rethink your design here.
I'm wondering if there's a way to return an object instead of a string when calling an object without any methods.
For instance:
class Foo
def initialize
#bar = Bar.new
end
end
Is there any way to define the Foo class so that the following happens:
foo = Foo.new
foo #returns #bar
In the specific case I'm interested in I'm using a presenter in a Rails view. The presenter sets up one main object and then loads a bunch of related content. The important part looks like this:
class ExamplePresenter
def initialize( id )
#example = Example.find( id )
end
def example
#example
end
...
end
If I want to return the example used by the ExamplePresenter I can call:
#presenter = ExamplePresenter.new(1)
#presenter.example
It would be nice if I could also return the example object by just calling:
#presenter
So, is there a way to set a default method to return when an object is called, like to_s but returning an object instead of a string?
If I understand correctly, you want to return the instance of Example when you call the ExamplePresenter instance. Such a direct mechanism does not exist in any language, and even if it did, it would block all access to the ExamplePresenter instance and its methods. So it is not logical.
There is something you can do however. You can make the ExamplePresenter class delegate methods to the Example instance inside it. Effectively you do not get a real Example from #presenter but you get an ExamplePresenter that passes all eligible methods into its internal Example effectively acting in behalf of it.
Some ways of doing this is:
method_missing
class ExamplePresenter
… # as defined in the question
def method_missing symbol, *args
if #example.respond_to?(symbol)
#example.send(symbol, *args)
else
super
end
end
end
This will pass any method call down to the internal Example if the ExamplePresenter cannot respond to it. Be careful, you may expose more than you want of the internal Example this way, and any method already defined on ExamplePresenter cannot be passed along.
You can use additional logic inside method_missing to limit exposure or pre/post process the arguments/return values.
Wrapper methods
You can define wrapper methods on ExamplePresenter that do nothing but pass everything to the internal Example. This gives you explicit control on how much of it you want to expose.
class ExamplePresenter
… # as before
def a_method
#example.a_method
end
def another_method(argument, another_argument)
#example.another_method(argument, another_argument)
end
end
This gets tedious fast, but you can also add logic to alter arguments before passing it along to the Example or post process the results.
You can also mix and match the above two methods
Delegator library
There is a library in Ruby stdlib called Delegator built exactly for this purpose. You may look into it.
Although this is not recommended, you can do:
class Foo
def self.new
#bar = Bar.new
end
end
If you actually do need to create an instance of Foo, then
class << Foo
alias original_new :new
end
class Foo
def self.new
self.original_new # It will not be useful unless you assign this to some variable.
#bar = Bar.new
end
end