Creating class with name dynamically via const_missing - ruby

I have this module:
module Api
module ObjectMapper
def self.const_missing const_name
anon_class = Class.new do
def self.foo
puts self.class.name
end
end
const_set const_name, anon_class
end
end
end
I want to be able to define an anonymous class at runtime with a method foo that can be called with Api::ObjectMapper::User::foo. That function should print User to the screen. Everything that I have tried has resulted in some sort of error or the function prints Class to the screen.
How do I fix my class and method definitions so that self.class.name resolves correctly?

The name of a class is just the first constant that refers to it. The only problem with your original code is that you are using self.class.name instead of self.name:
module Api
module ObjectMapper
def self.const_missing const_name
self.const_set const_name, Class.new{
def self.foo
name.split('::').last
end
}
end
end
end
p Api::ObjectMapper::User, #=> Api::ObjectMapper::User
Api::ObjectMapper::User.name, #=> "Api::ObjectMapper::User"
Api::ObjectMapper::User.foo #=> "User"
When you define a class method (singleton method on a class) the self is the class. The self.class is therefore always Class, whose name is "Class".
Original answer, which returns "User" instead of "Api::ObjectMapper::User"
One way (no better than your closure-based solution) is to use an instance variable on the class:
module Api
module ObjectMapper
def self.const_missing const_name
anon_class = Class.new do
def self.foo
puts #real_name
end
end
anon_class.instance_variable_set(:#real_name,const_name)
const_set const_name, anon_class
end
end
end
Api::ObjectMapper::User.foo
#=> User
A couple alternative, tighter syntaxes:
def self.const_missing const_name
const_set const_name, Class.new{
def self.foo; puts #real_name end
}.tap{ |c| c.instance_eval{ #real_name = const_name } }
end
def self.const_missing const_name
const_set const_name, Class.new{
def self.foo; puts #real_name end
}.instance_eval{ #real_name = const_name; self }
end

I found a solution. Since you are defining the anonymous class from within the scope of the const_missing method, you have const_name available to you which is the name of the class you're defining. I'm not sure if that's the best solution, but it does work. You have to redefine your class like this:
anon_class = Class.new do
define_singleton_method(:foo) do
puts const_name
end
end

You can also define your foo method as class method
def self.const_missing const_name
anon_class = Class.new do
def self.foo
puts self.class.name
end
end
end

Related

call before methods in model on ruby

This my implementation to developing way to run code before all method in your model
The call "before_hook :months_used" method need to be on bottom of class to the ExecutionHooks can get the instance_method loaded in the module. I would like to load the instance methods on top
class BalanceChart < BalanceFind
include ExecutionHooks
attr_reader :options
def initialize(options = {})
#options = options
#begin_at = #options[:begin_at]
end
def months_used
range.map{|date| I18n.l date, format: :month_year}.uniq!
end
before_hook :months_used
end
module ExecutionHooks
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def before
#hooks.each do |name|
m = instance_method(name)
define_method(name) do |*args, &block|
return if #begin_at.blank? ## the code you can execute before methods
m.bind(self).(*args, &block) ## your old code in the method of the class
end
end
end
def before_hook(*method_name)
#hooks = method_name
before
end
def hooks
#hooks ||= []
end
end
end
You can do this with prepend. prepend is like include in that it adds a module to the ancestors of the class, however instead of adding it after the class it adds it before.
This means that if a method exists both in the prepended module and the class then the module implementation is called first (and it can optionally call super if it wants to call the base class).
This allows you to write a hooks module like so:
module Hooks
def before(*method_names)
to_prepend = Module.new do
method_names.each do |name|
define_method(name) do |*args, &block|
puts "before #{name}"
super(*args,&block)
end
end
end
prepend to_prepend
end
end
class Example
extend Hooks
before :foo, :bar
def foo
puts "in foo"
end
def bar
puts "in bar"
end
end
In real use you would probably want to stash that module somewhere so that each call to before doesn't create a new module but that is just an inplementation detail
#rathrio This is my implementation using method_added that you talked. Thanks
module ExecutionHooks
def validation
p "works1"
end
def self.included(base)
base.send :extend, ClassMethods
end
end
module ClassMethods
attr_writer :hooked
def hooked
#hooked ||= []
end
def method_added(method)
return if #hooks.nil?
return unless #hooks.include?(method)
m = self.instance_method(method)
unless hooked.include?(method)
hooked << method
define_method(method) do |*args, &block|
validation
m.bind(self).(*args, &block) ## your old code in the method of the class
end
end
end
def before_hook(*method_name)
#hooks = method_name
end
def hooks
#hooks ||= []
end
end
end
class BalanceChart < BalanceFind
include ExecutionHooks
before_hook :months_data, :months_used, :debits_amount, :test
def test
"test"
end
end
Instead of redefining the method when calling before_hook, you could override the method_added hook to prepend your before hooks to a method right after it was defined. This way your before_hook calls can be (actually, must be) placed at the top of the class definition.

Ruby's `respond_to?` do not work just after definition?

I have a module that defines a method if it is not already defined. This is the case of ActiveRecord's attributes as theirs getters and setters are not defined as methods.
module B
def create_say_hello_if_not_exists
puts respond_to?(:say_hello)
define_method :say_hello do
puts 'hello'
end unless respond_to?(:say_hello)
end
end
class A
def say_hello
puts 'hi'
end
puts respond_to?(:say_hello, true)
extend B
create_say_hello_if_not_exists
end
A.new.say_hello
The expected result is hi, but ruby prints hello. Why?
Maybe related to Confused about "respond_to?" method
Try this.
module B
def create_say_hello_if_not_exists
puts method_defined?(:say_hello)
define_method :say_hello do
puts 'hello'
end unless method_defined?(:say_hello)
end
end
class A
def say_hello
puts 'hi'
end
puts method_defined?( :say_hello )
extend B
create_say_hello_if_not_exists
end
A.new.say_hello
The reason why respond_to?(:say_hello) is returning false is due to the fact class A has say_hello as instance method and since you are extending class B the create_say_hello_if_not_exists is declared as class method and it does not find say_hello.
Changing the code to the following would do the trick. I'm declaring say_hello in class A as class method and am calling it in a static manner.
module B
def create_say_hello_if_not_exists
puts respond_to?(:say_hello)
define_method :say_hello do
puts 'hello'
end unless respond_to?(:say_hello)
end
end
class A
def self.say_hello
puts 'hi'
end
extend B
create_say_hello_if_not_exists
end
A.say_hello

How do have a class method that redefines other class methods?

I want to wrap all class methods for a module with logging, like this:
module SomeModule
def self.foo
puts "bar"
end
class << self
SomeModule.methods(false).each do |method|
alias_method "old_#{method}".to_sym, method
define_method method do |*args|
puts "Called method: #{method}"
send "old_#{method}", *args
end
end
end
end
SomeModule.foo
#-> Called method: foo
#-> bar
That works perfectly. But what if I wanted the wrapping to only happen when I called a method? How could I make this happen when you call
module SomeModule
def self.foo
puts "bar"
end
def self.add_logging_to_all_methods
#???
end
end
SomeModule.add_logging_to_all_methods
SomeModule.foo
#-> Called method: foo
#-> bar
I’m not going to ask what you want this for, but here it is:
module SomeModule
def self.foo
puts "bar"
end
def self.add_logging_to_all_methods
eigenclass = class << self; self; end
methods(false).each do |method|
eigenclass.class_eval do
alias_method "old_#{method}".to_sym, method
define_method method do |*args|
puts "Called method: #{method}"
send "old_#{method}", *args
end
end
end
end
end
SomeModule.add_logging_to_all_methods
SomeModule.foo
Be aware that this also adds “logging” to add_logging_to_all_methods, but only after invoking it, so if you only invoke it once, you should not see anything wrong.
What eigenclass means is the “instance” where you add this methods foo and add_logging_to_all_methods. By returning self inside the class << self; end block I’m getting that instance. Then I ask the block to be evaluated in the context of that instance, which does more or less the same as your previous method.
There may be an easier way to do it.
You can apply that on all classes:
ObjectSpace.each_object.select { |o| o.is_a? Class }.each do |klass|
klass.class_eval do
methods(false).each do |method|
alias_method "old_#{method}".to_sym, method
define_method method do |*args|
puts "Called method: #{method}"
send "old_#{method}", *args
end
end
end rescue nil
end
Ah nevermind, just placing the whole class << self block in the method works okay.

Singleton method error from bind when called with the same metaclass

I'm writing aspect-ish code more or less lifted from the chosen solution for this question that looks like the following:
class Module
def add_logging klass, *method_names
method_names.each do |method_name|
original_method = instance_method method_name
define_method method_name do |*args, &blk|
log.debug("#{klass}.#{method_name} called")
original_method.bind(klass).call(*args, &blk)
end
end
end
end
The solution in the other post doesn't require the klass parameter, but it only works for instance methods, whereas I hope to call my code like this:
module MyModule
def MyModule.module_method
p "hello"
end
class << self
add_logging self, :module_method1
end
end
Unfortunately when I run this code I get in 'bind': singleton method called for a different object (TypeError). Seeing as I pass self in the context of the class << self block, I don't understand why the bind call in the above code thinks it isn't binding to the exact same metaclass.
This should work for you:
class Module
def add_logging(*method_names)
method_names.each do |method_name|
original_method = method(method_name).unbind
define_singleton_method(method_name) do |*args, &blk|
puts "#{self}.#{method_name} called"
original_method.bind(self).call(*args, &blk)
end
end
end
end
# class method example
module MyModule
def self.module_method1
puts "hello"
end
add_logging :module_method1
end
MyModule.module_method1
# output:
#
# MyModule.module_method1 called
# hello

How can I intercept method call in ruby?

I currently have a superclass which has a function that I want all the subclass to call within each of its function. The function is supposed to behave like a before_filter function in rails but I am not sure on how to go about implementing before_filter. Here is an example
class Superclass
def before_each_method
puts "Before Method" #this is supposed to be invoked by each extending class' method
end
end
class Subclass < Superclass
def my_method
#when this method is called, before_each_method method is supposed to get invoked
end
end
This is one way to do it:
class Superclass
def before_each_method name
p [:before_method, name]
end
def self.method_added name
return if #__last_methods_added && #__last_methods_added.include?(name)
with = :"#{name}_with_before_each_method"
without = :"#{name}_without_before_each_method"
#__last_methods_added = [name, with, without]
define_method with do |*args, &block|
before_each_method name
send without, *args, &block
end
alias_method without, name
alias_method name, with
#__last_methods_added = nil
end
end
class SubclassA < Superclass
def my_new_method
p :my_new_method
end
def my_new_other_method
p :my_new_other_method
end
end
SubclassA.new.my_new_method
SubclassA.new.my_new_other_method
This will create a wrapper method using the alias_method_chaining method as soon as the method you'd like to wrap is defined in the subclass.
This is my solution:
require 'active_support/all'
module BeforeEach
extend ActiveSupport::Concern
module InstanceMethods
def before_each
raise NotImplementedError('Please define before_each method')
end
end
module ClassMethods
def method_added(method)
method = method.to_s.gsub(/_with(out)?_before$/, '')
with_method, without_method = "#{method}_with_before", "#{method}_without_before"
return if method == 'before_each' or method_defined?(with_method)
define_method(with_method) do |*args, &block|
before_each
send(without_method, *args, &block)
end
alias_method_chain(method, :before)
end
end
end
To use it, just include BeforeEach into your class like so:
class Superclass
include BeforeEach
def before_each
puts "Before Method" #this is supposed to be invoked by each extending class' method
end
end
class Subclass < Superclass
def my_method
#when this method is called, before_each_method method is supposed to get invoked
end
end
Subclass.new.my_method
# => Before Method
Hopefully this will work for you!
class BalanceChart < BalanceFind
include ExecutionHooks
attr_reader :options
def initialize(options = {})
#options = options
#begin_at = #options[:begin_at]
end
def months_used
range.map{|date| I18n.l date, format: :month_year}.uniq!
end
before_hook :months_data, :months_used, :debits_amount
end
module ExecutionHooks
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def before
#hooks.each do |name|
m = instance_method(name)
define_method(name) do |*args, &block|
return if #begin_at.blank? ## the code you can execute before methods
m.bind(self).(*args, &block) ## your old code in the method of the class
end
end
end
def before_hook(*method_name)
#hooks = method_name
before
end
def hooks
#hooks ||= []
end
end
end

Resources