Jackson Will
2018-05-31 13:25:51 UTC
I am completely new to ruby though I have several years experience in programming. My question is why following code's class X can directly refer to state (for defining method block) without any include or require keyword? And how can I access to state method value (in class X) after those state blocks are initialized (so I can observe values gets defined or executed in that block)? Thanks
class Module
def state(&block)
meth_name = Module.make_state_meth_name(self)
puts "meth name: #{meth_name}"
define_method(meth_name, &block)
end
def self.make_state_meth_name(klass)
@state_meth_id ||= 0
r = "__state#{@state_meth_id}__#{Module.get_class_name(klass)}".to_sym
@state_meth_id += 1
return r
end
def self.get_class_name(klass)
(klass.name.nil? or klass.name == "") \
? "Anon#{klass.object_id}" \
: klass.name.split("::").last
end
end
class X
state do
puts "abc"
end
state do
puts "xyz"
end
end
x = X.new
class Module
def state(&block)
meth_name = Module.make_state_meth_name(self)
puts "meth name: #{meth_name}"
define_method(meth_name, &block)
end
def self.make_state_meth_name(klass)
@state_meth_id ||= 0
r = "__state#{@state_meth_id}__#{Module.get_class_name(klass)}".to_sym
@state_meth_id += 1
return r
end
def self.get_class_name(klass)
(klass.name.nil? or klass.name == "") \
? "Anon#{klass.object_id}" \
: klass.name.split("::").last
end
end
class X
state do
puts "abc"
end
state do
puts "xyz"
end
end
x = X.new