Have a parent class's method access the subclass's constants - ruby

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

Related

Class variables and inheritance. Subclass specific variables?

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

Insert code into the beginning of each method of a class

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"

Extracting ancestors upto "me"

Given
class Bird
def self.bird_ancestors
ancestors.first(ancestors.find_index(Bird)+1)
end
end
class Duck < Bird
end
class FeatheredDuck < Duck
end
FeatheredDuck.bird_ancestors => [FeatheredDuck,Duck,Bird]
Duck.bird_ancestors => [Duck,Bird]
Bird.bird_ancestors => [Bird]
How can I reference the Bird within Bird without having it be explicit? I know self and __class__ doesnt work.
Inside a class method, self refers to the current class object:
class Bird
def self.foo
self
end
end
p Bird.foo # => "Bird"
This will do it:
class Bird
def self.bird_ancestors
ancestors.take_while { |c| c.respond_to? __method__ }
end
end
class Duck < Bird
end
class FeatheredDuck < Duck
end
FeatheredDuck.bird_ancestors #=> [FeatheredDuck, Duck, Bird]
Duck.bird_ancestors #=> [Duck, Bird]
Bird.bird_ancestors #=> [Bird]
select also works, but take_while (suggested by #Aditya) is better because it stops searching ancestors once false is returned from the block.
you can do something like this:
class Bird
def self.bird_ancestors
class_name = method(__method__).owner.to_s.gsub(/#<Class:|>/,'')
ancestors.first(ancestors.map{|x| x.to_s}.find_index(class_name)+1)
end
end
(__method__ is the current method)

Struct.new on a class definition

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.

how to get child class variable back into parent class in ruby

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

Resources