class Dog
def bark
"woof"
end
end
dog = Dog.new
dog.bark
self
is a reference to the object in scope
class Dog
def speak
self.bark
end
end
dog.speak
new
and
superclass
for example
Dog.superclass # => Animal
Dog.new # => instance of Dog
Dog.class # => Class
def Dog
def self.type
:mammal
end
end
Dog.type # => :mammal
Then that should be equivalent to
def Dog
end
def Dog.type
:mammal
end
Dog.type # => :mammal
dog = Dog.new
dog.bark # => "woof"
def dog.bark
"meow"
end
dog.bark # => "meow"
other_dog = Dog.new
dog.bark # => "woof"
class << object
to open up that object’s eigenclass
Object#singleton_class
will return your eigenclass
class Dog
class << self
def type
:mammal
end
end
end
class << Dog
def type
:mammal
end
end
self
is referring to
define_method
Class#define_method
takes a block and defines a method on the class
Class#attr_accessor
class Class
def attr_accessor(attr)
define_method(attr) do
instance_variable_get "@#{attr}"
end
define_method("#{attr}=") do |val|
instance_variable_set "@#{attr}", val
end
end
end
method_missing
method_missing
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.pension = 300
puts person.name # -> "John Smith"
puts person.age # -> 70
puts person.address # -> nil
class OpenStruct
def initialize
@attrs = {}
end
def method_missing(method, val = nil)
if method =~ /^(\w+)=$/
# Setter
@attrs[$1] = val
elsif method =~ /\w+/
# Getter
@attrs[method]
else
# Die
super
end
end
end
instance_eval
class Dog
private
def bark
"woof"
end
end
dog = Dog.new
dog.instance_eval { bark } # => "woof"
server {
listen 80;
server_name domain.com *.domain.com;
return 301 $scheme://www.domain.com$request_uri;
}
server {
listen 80;
server_name www.domain.com;
index index.html;
root /home/domain.com;
}
feature "Widget management" do
scenario "User creates a new widget" do
visit "/widgets/new"
fill_in "Name", :with => "My Widget"
click_button "Create Widget"
expect(page).to have_text("Widget was successfully created.")
end
end