metaprogramming
Nothing to display jet.
Nothing to display jet.
A colleague of mine proposed an idea for a new syntax for instantiating object in #rails:
User.create! do
nickname = 'makaroni4'
email = 'my_email@gmail.com'
end
As you can see there is no variable passed to a block and there is no context (self etc) inside the block. Is it possible? Under the cut there is an explanation of this case and implementation of similar syntax. More under the cut
class User < ActiveRecord::Base
has_many :friends, class_name: :Buddy
end
u = User.new
klass = u.association(:friends).klass
klass # => Buddy
#Bash? #Metaprogramming? WTF? Turns out, bash's everything-is-a-string philosophy makes it pretty awesome for metaprogramming. More under the cut
In this post I will show how to redefine attr_reader method to have default value.
It will be more abstract solution than common:
def some_variable
@some_variable || 'default_value'
end
Don't forget that self.included method in module is executed in the end:
module Gangster
def self.included(base)
puts "Inside self.included"
end
puts "Outside self.included"
def shoot
puts "Tra ta ta ta ta!"
end
end
class Human
include Gangster
end
# => Outside self.included
# => Inside self.included
Basically this is dynamic monkey patch of all instance_methods. More under the cut