I came across some interesting Ruby code today.
class MeetingReminderJob < Struct.new(:user, :meeting)
def perform
send_reminder(user, meeting)
end
end
What is the purpose of the < Struct.new(:user, :meeting)?
Struct is a ruby class, it created a Class object that contains attributes and accessors, you don't need define a class explicitly. In the api ,you can find more details : http://www.ruby-doc.org/core-1.9.3/Struct.html.
In your case , it create a class that contains 2 attributes named "user" and "meeting", then class MeetingReminderJob inherits it.
Here's another example:
class Animal
def greet
puts "Hi. I'm an animal"
end
end
def get_class
return Animal
end
class Dog < get_class
def warn
puts "Woof."
end
end
Dog.new.greet
Dog.new.warn
--output:--
Hi. I'm an animal
Woof.
And another:
class Dog < Class.new { def greet; puts "Hi"; end }
def warn
puts "Woof."
end
end
Dog.new.greet
Dog.new.warn
--output:--
Hi
Woof.
Related
I am struggling a bit with subclassing and class variables. I was expecting the class variables set by a class method call of the subclass to be specific to that subclass, but I see them being set in the super class.
For example, if I run the following code:
class Obj
##can_say = []
def self.says word
##can_say.push(word)
end
def self.listens_to calling
define_method calling do
"I say #{##can_say}"
end
end
end
class Dog < Obj
says "woof"
says "bark bark"
listens_to "goodboy"
end
class Cat < Obj
says "meaow"
says "purr"
listens_to "lord"
end
cat = Cat.new
dog = Dog.new
puts("Dog: #{dog.goodboy}")
puts("Cat: #{cat.lord}")
I get:
ruby/test$ ruby test.rb
Dog: I say ["woof", "bark bark", "meaow", "purr"]
Cat: I say ["woof", "bark bark", "meaow", "purr"]
I was expecting:
ruby/test$ ruby test.rb
Dog: I say ["woof", "bark bark"]
Cat: I say ["meaow", "purr"]
Is there a way to achieve that?
I kind of found a way:
class Obj
class << self
attr_accessor :can_say
end
def self.says word
if #can_say.nil?
#can_say = Array.new
end
#can_say.push(word)
end
def self.listens_to calling
define_method calling do
"I say #{self.class.can_say}"
end
end
end
class Dog < Obj
says "woof"
says "bark bark"
listens_to "goodboy"
end
class Cat < Obj
says "meaow"
says "purr"
listens_to "lord"
end
cat = Cat.new
dog = Dog.new
puts("Dog: #{dog.goodboy}")
puts("Cat: #{cat.lord}")
Now if I can somehow get rid of:
if #can_say.nil?
#can_say = Array.new
end
How can I dynamically and easily insert code into the beginning of each method of a class and subclasses without actually inserting it manually? I want something like a macros.
class C1
def m1
#i_am = __method__
end
def m2
#i_am = __method__
end
end
This is one of the examples where I want to avoid repetition.
I initially misinterpreted the question (but have left my original answer after the horizontal line below). I believe the following may be what you are looking for.
class C1
[:m1, :m2].each do |m|
define_method(m) do |name|
#i_am = __method__
puts "I'm #{name} from method #{#i_am}"
end
end
end
C1.instance_methods(false)
#=> [:m1, :m2]
c1 = C1.new
#=> #<C1:0x007f94a10c0b60>
c1.m1 "Bob"
# I'm Bob from method m1
c1.m2 "Lucy"
# I'm Lucy from method m2
My original solution follows.
class C1
def add_code_to_beginning(meth)
meth = meth.to_sym
self.class.send(:alias_method, "old_#{meth}".to_sym, meth)
self.class.send(:define_method, meth) do
yield
send("old_#{meth}".to_sym)
end
end
end
Module#alias_method
and Module#define_method are private; hence the need to use send.
c = C1.new
#=> #<C1:0x007ff5e3023650>
C1.instance_methods(false)
#=> [:m1, :m2, :add_code_to_beginning]
c.add_code_to_beginning(:m1) do
puts "hiya"
end
C1.instance_methods(false)
#=> [:m1, :m2, :add_code_to_beginning, :old_m1]
c.m1
# hiya
#=> :m1
You can use a rails like class decorators to that. The piece of code below is rendering a method called before_action defined in the Base class of the ActiveRecord module. The Test class is inherited from the ActiveRecord. The define_method is used if we want to call something explicitly from the Base class.
module ActiveRecord
class Base
def self.before_action(name)
puts "#{name}"
puts "inside before_action of class Base"
define_method(name) do
puts "Base: rendering code from Base class"
end
end
end
end
class Test < ActiveRecord::Base
before_action :hola
def render()
puts "inside render of class Test"
end
end
test = Test.new
test.render
test.hola
It has the output
hola
inside before_action of class Base
inside render of class Test
Base: rendering code from Base class
So, before running the render method it runs the before_action method in the Base class. It can be applied to all other methods in the Test class. This is a way of representing macros in ruby.
Assuming that the function is the same, you could create a module and include it in your classes.
Example:
module MyModule
def test_method
puts "abc"
end
end
class MyClass
include MyModule
def my_method
puts "my method"
end
end
inst = MyClass.new
inst.test_method # => should print "abc"
inst.my_method # => should print "my method"
I have this module
module MyModule
def self.foo()
puts "A"
end
end
And this mixin class
class ParentClass
include MyModule
...other code
end
Can I overwrite the foo method in a child class like this or is there a better way?
class ChildClass < ParentClass
def self.foo()
puts "B"
end
... other code
end
You cannot include class methods directly:
module MyModule
def self.foo() puts "A" end
end
class ParentClass
include MyModule
end
ParentClass.methods.include?(:foo)
#=> false
ParentClass.instance_methods.include?(:foo)
#=> false
Instead, use Object#extend, which converts instance methods in MyModule to class methods in ParentClass:
module MyModule
def foo() puts "A" end
end
class ParentClass
extend MyModule
end
ParentClass.methods.include?(:foo)
#=> true
ParentClass.foo
A
class ChildClass < ParentClass
def self.foo() puts "B" end
end
ChildClass.foo
B
So, you may ask, what's the point of having class methods in a module? They can be present when the module is not used as a mixin, or has a combination of instance and class methods. The module's class methods are simply helper functions:
module A
def self.say
puts "It's a cat."
end
def say
puts "It's a dog."
end
end
class B
include A
end
A.say
It's a cat
B.new.say
It's a dog.
It is my impression that most modules that contain class methods tend to contain no instance methods; that is, they are not used as mix-ins. Readers are encouraged to correct me if I am wrong about that.
A common way to include some instance methods and extend others is to use the callback Module#included:
module A
def a; end
def self.included(klass)
klass.extend B
end
module B
def b; end
end
end
class C
include A
end
C.instance_methods.include?(:a)
#=> true
C.methods.include?(:b)
#=> true
I would like to create a base class to handle all the methods. How would I achieve this using ruby in this scenario?
class Dog
def initialize
#breed = "good breed"
end
def show_dog
puts "#{self.class.first_name} of breed #{#breed}"
end
end
class Lab < Dog
attr_reader :first_name
def initialize
#first_name = "good dog"
end
end
lb = Lab.new()
lb.show_dog
The expected result would be "good dog of breed good breed"
Thank you in advance :)
self.class.first_name doesn't do what you probably wanted to do. You need to use #first_name directly.
You need to call the parent class' constructor from the child class; it's not called automatically.
This works:
class Dog
def initialize
#breed = "good breed"
end
def show_dog
puts "#{#first_name} of breed #{#breed}" ### <- Changed
end
end
class Lab < Dog
attr_reader :first_name
def initialize
super ### <- Added
#first_name = "good dog"
end
end
lb = Lab.new()
lb.show_dog
self.class.first_name means Lab.first_name, not Lab's instance lb.first_name
For example:
class Animal
def make_noise
print NOISE
end
end
class Dog < Animal
NOISE = "bark"
end
d = Dog.new
d.make_noise # I want this to print "bark"
How do I accomplish the above? Currently it says
uninitialized constant Animal::NOISE
I think that you don't really want a constant; I think that you want an instance variable on the class:
class Animal
#noise = "whaargarble"
class << self
attr_accessor :noise
end
def make_noise
puts self.class.noise
end
end
class Dog < Animal
#noise = "bark"
end
a = Animal.new
d = Dog.new
a.make_noise #=> "whaargarble"
d.make_noise #=> "bark"
Dog.noise = "WOOF"
d.make_noise #=> "WOOF"
a.make_noise #=> "whaargarble"
However, if you are sure that you want a constant:
class Animal
def make_noise
puts self.class::NOISE
# or self.class.const_get(:NOISE)
end
end
one way to do it without class instance variables:
class Animal
def make_noise
print self.class::NOISE
end
end
class Dog < Animal
NOISE = "bark"
end
d = Dog.new
d.make_noise # prints bark
I think you have the wrong concept here. Classes in Ruby are similar to classes in Java, Smalltalk, C#, ... and all are templates for their instances. So the class defines the structure and the behavior if its instances, and the parts of the structure and behavior of the instances of its subclasses but not vice versae.
So direct access from a superclass to a constant in a subclass is not possible at all, and that is a good thing. See below how to fix it. For your classes defined, the following things are true:
class Animal defines the method make_noise.
instances of class Animal may call the method make_noise.
class Dogdefines the constant NOISE with its value.
instances of Dog and the class Dog itself may use the constant NOISE.
What is not possible:
Instances of Animal or the class Animal itself have access to constants of the class Dog.
You may fix that by the following change:
class Animal
def make_noise
print Dog::NOISE
end
end
But this is bad style, because now, your superclass (which is an abstraction about Dog and other animals) knows now something that belongs to Dog.
A better solution would be:
Define an abstract method in class Animal which defines that make_noise should be defined. See the answer https://stackoverflow.com/a/6792499/41540.
Define in your concrete classes the method again, but now with the reference to the constant.
If you're doing this to configure your sub classes so that the base class has access to the constants then you can create a DSL for them like this:
module KlassConfig
def attr_config(attribute)
define_singleton_method(attribute) do |*args|
method_name = "config_#{attribute}"
define_singleton_method method_name do
args.first
end
define_method method_name do
args.first
end
end
end
end
class Animal
extend KlassConfig
attr_config :noise
def make_noise
puts config_noise
end
end
class Dog < Animal
noise 'bark'
end
This way is a bit more performant as on each method call you don't have to introspect the class to reach back (or is it forward?) for the constant.
If you want it the Object-Oriented Way (TM), then I guess you want:
class Animal
# abstract animals cannot make a noise
end
class Dog < Animal
def make_noise
print "bark"
end
end
class Cat < Animal
def make_noise
print "meow"
end
end
d = Dog.new
d.make_noise # prints bark
c = Cat.new
c.make_noise # prints meow
If you want to refactor to prevent duplicating the code for print:
class Animal
def make_noise
print noise
end
end
class Dog < Animal
def noise
"bark"
end
end
class Cat < Animal
def noise
if friendly
"meow"
else
"hiss"
end
end
end
d = Dog.new
d.make_noise # prints bark
c = Cat.new
c.make_noise # prints meow or hiss