I know global variables should never be used but right now it's the only thing that I can get to work. So I'm looking for alternatives. What I want to do is pass #array which is is in method two in class New, to method one. The only way I was able to accomplish this is with $array.
module Test::Abc
class << self
def one
....
end
class New
def two
#array=[]
end
end
end
end
Here's what I did to get the result I needed...
module Test::Abc
class << self
def one(array)
....
end
end
class New
def two
#array=[]
array=#array
Test::Abc::one(array)
end
end
end
Here's what I came up with as a solution...
module Test::Abc
class << self
def one(array)
....
end
end
class New
def two
#array=[]
array=#array
Test::Abc::one(array)
end
end
end
Along with your answer, this should also work (slight modification):
module Test::Abc
class << self
def one(array)
....
end
end
class New
def two
#array=[]
Test::Abc::one(#array)
end
end
end
Related
In Rails we can define a class like:
class Test < ActiveRecord::Base
before_initialize :method
end
and when calling Test.new, method() will be called on the instance. I'm trying to learn more about Ruby and class methods like this, but I'm having trouble trying to implement this in plain Ruby.
Here's what I have so far:
class LameAR
def self.before_initialize(*args, &block)
# somehow store the symbols or block to be called on init
end
def new(*args)
## Call methods/blocks here
super(*args)
end
end
class Tester < LameAR
before_initialize :do_stuff
def do_stuff
puts "DOING STUFF!!"
end
end
I'm trying to figure out where to store the blocks in self.before_initialize. I originally tried an instance variable like #before_init_methods, but that instance variable wouldn't exist in memory at that point, so I couldn't store or retrieve from it. I'm not sure how/where could I store these blocks/procs/symbols during the class definition, to later be called inside of new.
How could I implement this? (Either having before_initialize take a block/proc/list of symbols, I don't mind at this point, just trying to understand the concept)
For a comprehensive description, you can always check the Rails source; it is itself implemented in 'plain Ruby', after all. (But it handles lots of edge cases, so it's not great for getting a quick overview.)
The quick version is:
module MyCallbacks
def self.included(klass)
klass.extend(ClassMethods) # we don't have ActiveSupport::Concern either
end
module ClassMethods
def initialize_callbacks
#callbacks ||= []
end
def before_initialize(&block)
initialize_callbacks << block
end
end
def initialize(*)
self.class.initialize_callbacks.each do |callback|
instance_eval(&callback)
end
super
end
end
class Tester
include MyCallbacks
before_initialize { puts "hello world" }
end
Tester.new
Left to the reader:
arguments
calling methods by name
inheritance
callbacks aborting a call and supplying the return value
"around" callbacks that wrap the original invocation
conditional callbacks (:if / :unless)
subclasses selectively overriding/skipping callbacks
inserting new callbacks elsewhere in the sequence
... but eliding all of those is what [hopefully] makes this implementation more approachable.
One way would be by overriding Class#new:
class LameAR
def self.before_initialize(*symbols_or_callables, &block)
#before_init_methods ||= []
#before_init_methods.concat(symbols_or_callables)
#before_init_methods << block if block
nil
end
def self.new(*args, &block)
obj = allocate
#before_init_methods.each do |symbol_or_callable|
if symbol_or_callable.is_a?(Symbol)
obj.public_send(symbol_or_callable)
else
symbol_or_callable.(obj)
end
end
obj.__send__(:initialize, *args, &block)
end
end
class Tester < LameAR
before_initialize :do_stuff
def do_stuff
puts "DOING STUFF!!"
end
end
I am learning ruby meta-programming's meta classes concept. i am trying to define method dynamically inside meta-class but the problem which i am facing is i am not able to access "name" inside meta-class.
Below is my code.
class Abc
def add_method(name)
class << self
define_method "#{name}" do
end
end
end
end
a = Module.const_get("Abc").new
a.add_method("my_method")
a.my_method
Ok. got solution after some online debugging. Below is the solution
class Abc
def add_method(name)
meta_class = class << self
self
end
meta_class.class_eval do
define_method "#{name}" do
end
end
end
end
a = Module.const_get("Abc").new
a.add_method("my_method")
a.my_method
I am unable to figure out or find any information on how to push the initialized object pointer to an array accessed from a class level variable. Here is an example.
Class Color
##colors = Array.new
def initialize
##colors << red
end
def self.list
##colors.each do |color|
puts color.to_hex
end
end
end
red = Color.new
Thanks guys for your help.
I would do it this way:
class Color
#colors = []
def self.new(*args, &blk)
#colors << super
end
def self.list
puts #colors.map(&:to_hex)
end
end
red = Color.new
Color.list
Personally, I feel uncomfortable doing class-level stuff in the instance initializer, it just doesn't feel right. The class is a completely independent object, having the instance know too much about the class smells of bad OO.
You can use self to reference the current instance of the class:
class Color
##colors = Array.new
def initialize
##colors << self
end
def self.list
##colors.each do |color|
puts color.to_hex
end
end
end
You should prefer class instance variables over class variables. Class variables are like globals - if you change it in a subclass it will also change the variable in the superclass. This is rarely the wanted effect. Here's #JKillian's code rewritten with class instance variables:
class Color
class << self
attr_accessor :colors
end
#colors = Array.new
def initialize
Color.colors << self
end
def self.list
#colors.each do |color|
puts color.to_hex
end
end
end
I'm trying to mix a module into a class, and I want some of the methods to behave as class methods and others to be instance methods.
However, I don't want to both include and extend the module. I'd rather just include it.
When I wrap the methods I want to be class methods in this notation, it works:
class <<
# ...
end
However, when I use this notation it doesn't work:
class << self
# ...
end
I suspect the self keyword is establishing an explicit binding to the module, rather than the class it gets mixed into. But I've not seen any documentation that recommends leaving the self keyword off when using the class << notation.
Does anyone know what's going on with this?
UPDATE: Here's some sample code for more clarity:
module M
class <<
def class_method
puts "From inside the class_method"
end
end
def instance_method
puts "From inside the instance_method"
end
end
class Object
include M
end
class C
end
C.class_method
obj = C.new
obj.instance_method
class << must always be followed by an object. Just class <<; end is a syntax error. In your case it looks like it works because of the following:
class <<
def class_method
puts "From inside the class_method"
end
end
is the same as
class << def class_method
puts "From inside the class_method"
end
end
which is the same as
temp = def class_method
puts "From inside the class_method"
end
class << temp
end
which is the same as
def class_method
puts "From inside the class_method"
end
class << nil
end
which is the same as
def class_method
puts "From inside the class_method"
end
Of course that doesn't actually define a class method. It defines an instance method.
Yeah, if you want to get a real self in your module you should use included callback. Something like this point you in the right direction:
module Bar
def self.included(base)
class << base
def class_method
"class_method"
end
end
end
end
class Foo
include Bar
end
p Foo.class_method # => "class_method"
I have a bunch of classes with similiar logic like this
class ApiWrapper
class << self
attr_accessor :app_id, :app_key
def configure
yield self
end
end
end
I want to extract this logic to a module similar to Ruby Struct class to be able to do something like this
class ApiWrapper
include Configurable.instance :app_id, :app_key
end
How can I do this?
From documentation
fred = Module.new do
def meth1
"hello"
end
def meth2
"bye"
end
end