According to the docs, in Rails models, transactions are made on either classes descending from ActiveRecord::Base or any instance of such a class. Some blog posts on the subject list the following alternatives:
ActiveRecord::Base.transaction do
User.transaction doUser descends from ActiveRecord::Base
#user.transaction do#user is an instance of User
self.class.transaction dowithin any model.rb where self is e.g. User
self.transaction dowithin any model.rb where self is e.g. an instance of User)
However, I'm missing another variation on this list: How about just transaction do within model.rb?
class User < ApplicationRecord
def foo
transaction do
# do stuff
end
end
end
Am I right to assume, that the self. is not really necessary since in the scope of a model instance method, self is always the model instance by default?
In Ruby the implicit recipient in an instance method is always the instance:
class Thing
def foo
inspect
end
end
irb(main):026:0> Thing.new.foo
=> "#<Thing:0x007fde95955828>"
Am I right to assume, that the self. is not really necessary since in
the scope of a model instance method, self is always the model
instance by default?
There is always an implicit recipient (self) in ruby. What it is depends on the context. In class methods its the class. Its "main" (the global object) if you are not in a class or module.
class Foo
inspect
end
# => "Foo"
def foo
inspect
end
# => "main"
You only have to explicitly use self where there is a need to disambiguate (like for example self.class). But there are many situations where it can help the readability of your code.
All of the options above are pretty much functionally equivalent:
ActiveRecord::Base.transaction connects to the DB for that environment from database.yml or ENV["DATABASE_URL"].
User.transaction or class.transaction can be used if you want to have different connections per model class or just don't like typing. All it really does is connection.transaction(options, &block).
The instance level self.transaction or #user.transaction just proxies to the class method. All it really does is self.class.transaction(options,&block);
Related
Let's say I have model Foo with bar column.
I'm quite used to define instance methods of model like this:
class Foo < ActiveRecord::Base
def do_smth
self.bar.capitalize!
end
end
But this is calling getter method on self, which should be just longer way of #bar.capitalize!.
As in Rails some things are hidden from eye (such as initializing Base class) I'm not sure. Will it work?
There is quite a bit of confusion going on here so lets start from the top:
Ruby is all about message passing - when you call a method on an object the implicit recipient is the object itself:
def do_smth
self.bar.capitalize!
end
is equivalent to:
def do_smth
bar.capitalize!
en
So lets take the following example:
class Thing
def initialize
#foo = 1
end
def test
foo # NameError: undefined local variable or method `foo'
end
def test2
#bar # nil
end
end
So, why does this fail? Because in Ruby instance variables are scoped to the instance and only accessible by using the sigil #. Ruby does not automatically map #foo to Thing#foo. Instance variables Ruby even lets you access uninitialized ivars (#bar).
That is unless we create an accessor:
class Thing
def foo
#foo
end
def test
foo # nil
end
end
Which can be done with the shorthand macros attr_reader and attr_accessor.
class Thing
attr_reader :foo # read only
attr_accessor :foo # rw
def test
foo # nil
end
end
This can be quite confusing if you start with Rails without learning how Ruby does OOP since Active Record reads your database tables and creates getters and setters "magically" for all your model attributes.
One thing that you need to remember in that case is that using #some_column will not call any getter/setter methods. Which can cause issues with the Rails dirty state tracking and in cases like date columns which typecast in the setter.
Note: This was the best title I could think of that wouldn't make this question seem like a dup. Please feel free to edit if it does not capture the point of the question
So I've been reading Advanced Rails and I had a question that wasn't fully answered by these posts:
When to use `self.foo` instead of `foo` in Ruby methods
In Ruby. How do I refer to the class from within class << self definition?
Why use "self" to access ActiveRecord/Rails model properties?
In my understanding, within a class definition, self refers to the object referenced by the pointer klass, so for the example of an eigenclass:
class A
class << self
def to.s
"Woot"
end
end
end
is the exact same as:
class << A
def to.s
"Woot"
end
end
This is because as you open up the class, ruby is creating a Class:A (virtual) class and assigning A's klass pointer to it. To my understanding this means that within the context of this class definition self == A
My question is (assuming my understanding as I've described it above is accurate) why then in an ActiveRecord::Base subclass in Rails does the use of self seem to be merely a disambiguation of the instance and not the class itself?
For example, if I have a class: A < ActiveRecord::Base with an attribute name, I cannot call A.name = "blah" outside the class definition. However, I CAN use ( and indeed MUST use ) self in assignment within the class definition like so: self.name = "blah".
If the use of self in Ruby refers to the Class object and not the instance, why does this work in ActiveRecord and how does Rails make the distinction?
Everything is a method
Anything you do with an object is a method. When you have a class like this:
class A
attr_accessor :foo
end
obj = A.new
obj.foo = 3
obj.foo #=> 3
It might feel weird, but you didn't make any assignment here. obj.foo = 3 is only a synthatic sugar for obj.send(:foo=, 3) so in fact, it executes foo= method. obj.foo is a method as well, it simply returns a value. This is because all the instance variables are private, and there is no other way to interact with them than inside the method. attr_accessor :foo is just a shortcut for:
def foo=(value)
#foo = value
end
def foo
#foo
end
Now, when ruby see any identifier like foo, it needs to find out what it is. Firstly it assumes it is a local variable, and if not, it tries to execute it as method on current self (see below). This means that:
class A
attr_accessor :foo
def bar
foo = 'bar'
end
end
a = A.new
a.bar #=> 'bar'
a.foo #=> nil
What happened? Interpretor first uses foo as an instance variable, it is not defined. But there is an assignment next to it, so it defines a new instance variable and make an assignment. If we want to use our setter we need to tell interpreter that it is not an instance varible:
class A
attr_accessor :foo
def bar
self.foo = 'bar'
end
end
a = A.new
a.bar #=> 'bar'
a.foo #=> 'bar'
I lied. Everything is an object
about self
self in ruby is very similar to this in javascript - it means different things in different context, and it can be easily changed at any point (obviously, not recommended).
First thing you need to know is that in Ruby every class is an object, namely it is an instance of class Class. When you do
class A
it is (almost, method below uses block and has access to external scope) equivalent to:
A = Class.new
self within a context of a class is always a class itself.
class A
self #=> A
def self.bar #=> this is class method
self #=> A
end
def foo #=> this is instance method
# We are no longer in context of class, but in context of the instance, hence
self #=> instance of A
end
end
Now, for any mutable object you can defined a singleton class. This is sort of weird concept - it is an extra subclass of the original class which only has a single instance. Since all the methods come from the class, this allows you to define extra methods on a particular instance of the method without affecting other object. In most of the cases, instance class is not needed and it is created when you access it for the first time. There are couple of ways to open it:
object.singleton_class do
self #=> instance class
end
class << object
self #=> instance class
end
Any method you defined within instance class is accessible only on that particular instance, hence this:
class A
self #=> A
class << A
# we are now in the instance class of A (which is an instance of Class class)
def foo
# So this is an instance method, however our instance is a class A
self #=> A
end
end
I am new to ruby and programming in general and am trying to grasp a few key concepts.
Given I have a class Dog, with the below characteristics.
class Dog
attr_accessor :type, :popularity, :total
def initialize(type = nil)
#type = type
end
def total_dogs
Dog.count
end
def total
Dog.where(:type => self.type).size
end
def popularity
total.to_f/total_dogs
end
end
What I am trying to understand, is how ruby persists attributes to an instance via getter/setter methods. Its clear to me that if I instantiate a new instance and then save attributes to that instance, those attributes are tied to that instance because if I look at the object the attributes appear as such:
#dog = Dog.new
#dog
=> #<Dog:0x007fa8689ea238 #type=nil>
Its easy for me to understand that as I pass the #dog object around its always going to have the #type attribute as nil.
However, the situation I am having trouble understanding is if I pass this #dog object to another class. Like if I did:
Owner.new(#dog)
When I am in the owner class and I call #dog.popularity how does it know the value of popularity for that instance? At runtime are all methods processed and then that instance just always is tied to the value at the time? Apologies if this makes no sense or I am way off.
When you do
#dog = Dog.new
You do two spearate things
1) Create an instance variable #dog for whatever object your code is currently inside
2) Instantiate a new instance of Dog (with all its methods and attributes) and assign a reference to it to #dog
#dog is a variable, that just happens to point at the Dog instance ("instance of class" generally same meaning as "object") you created at that point. You can set other variables to point to the same instance, and in Ruby this is generally how you pass data around. Objects contain instance variables, and those instance variables point to yet more objects.
Using the assignment operator (i.e "=") you can point a variable at any other object.
To answer your questions in turn:
When I am in the owner class and I call #dog.popularity how does it
know the value of popularity for that instance?
You have to be careful in Ruby (and OO languages in general) to differentiate between class and object in your descriptions and questions. Ruby I'm assuming you are referring to a line of code in the Owner class, and that you intend it to work with an owner object. I'd also assume that #dog is an attribute you have added to Owner.
In which case, Ruby knows because #dog points to the Dog object that you added to owner. Each Dog object has its own copy of all of Dog's instance variables. You do need to take care in Ruby though, because variables point to objects, that you aren't simply passing in the same Dog object to all the owners (i.e. they all effectively share a single dog). So you need to understand when you are creating new instances (via new) and when you are simply handling existing references.
At runtime are all methods processed and then that instance just
always is tied to the value at the time?
No. At runtime, basic Ruby will only perform the assignments that you have coded. Instance variables may not even exist until the code that assigns them has been run. If you use attr_reader etc methods, then the variables will at least exist (but will be nil unless you assign something during initialize)
Niel has a great answer for this, I just want to add something to it.
Counting Dogs :)
You need a class variable to do this..
class Dog
##count = 0 # this is a class variable; all objects created by this class share it
def initialize
##count += 1 # when we create a new Dog, we increment the count
end
def total
##count
end
end
There is another way to do this with "instance variables of the Class object" but that's a bit of an advanced topic.
Accessing Instance Variables
In Ruby, variables are really just references to objects / instances.
> x = 1
=> 1
> x.class
=> Fixnum
> 1.instance_variables
=> []
x is a reference to the object '1', which is an instance of class Fixnum.
The '1' object is an instance of Fixnum which does not contain any instance variables.
It is not different in any way from a reference to a new "Dog" instance.
Similarly, you can say x = Dog.new , then x is a reference to an instance of class Dog.
class Dog
attr_accessor :legs # this defines the 'legs' and 'legs=' methods!
end
x = Dog.new
x.instance_variables
=> [] # if you would assign legs=4 during "initialize", then it would show up here
x.legs = 4 # this is really a method call(!) to the 'legs' method
x.instance_variables # get created when they are first assigned a value
=> [:legs]
It does not matter if you pass such a reference to a method call, or to another class or just evaluate it by itself - Ruby knows it's an object reference, and looks inside the object and it's inheritance chain on how to resolve things.
Resolving Method Names
That was only the partial truth :) When interpreting x.legs , Ruby checks if there is a method in the class-inheritance chain of the object, which responds to that name 'legs'.
It is not magically accessing the instance variable with the same name!
We can define a method 'legs' by doing "attr_reader :legs" or "attr_accessor :legs", or by defining the method ourselves.
class Dog
def legs
4 # most dogs have 4 legs, we don't need a variable for that
end
end
x.legs # this is a method call! it is not directly accessing a :legs instance variable!
=> 4
x.instance_variables
=> [] # there is no instance variable with name ":legs"
and if we try to implement it as a method and an instance variable, this happens: :)
class Dog
attr_accessor :legs # this creates "def legs" and "def legs=" methods behind the scenes
def legs # here we explicitly override the "def legs" method from the line above.
4
end
end
x = Dog.new
x.legs # that's the method call we implemented explicitly
=> 4
x.legs = 3 # we can still assign something to the instance_variable via legs=
=> 3
x.legs # the last definition of a method overrides previous definitions
# e.g. it overrides the automatically generated "legs" method
=> 4
attr_accessor :legs is just a short hand notation for doing this:
class Dog
def legs
#legs
end
def legs=(value)
#legs = value
end
end
there is no magic way instance variable get automatically accessed. They are always accessed through a method, which can be overridden later.
I hope that makes sense to you
When you create an object, you don't need to use the # symbol. The variable is the object. So if you have multiple dogs, you'd do:
myDog = Dog.new(brown)
yourDog = Dog.new(white)
From there, you can say:
yourDog.type #white
myDog.type #brown
What you would NOT do is:
#dog = Dog.new #myDog
#dog = Dog.new #yourDog
If you need multiple versions of an object, you just give them different names. So if you create multiple dogs and pass them to other objects, they will work. For example:
Say your owner class is:
Class Owner
def initialize(pet)
puts "my pet is #{pet.type}"
end
Then using the instance variable would be:
me = Owner.new(myDog) #my pet is brown
you = Owner.new(yourDog) #my pet is white
Both "type" and "popularity" are methods on "dog" instances. Their definition is as follows:
class Dog
# getter
def type
#type
end
def popularity
total.to_f/total_dogs
end
end
This is roughly equivalent to:
class Dog
attr_accessor :type
def popularity
total.to_f/total_dogs
end
end
Note that attr_accessor is just a shortcut for defining a getter method. If you define a method yourself it is pointless to use attr_accessor:
class Dog
attr_accessor :popularity
# this will override getter defined by attr_accessor
def popularity
total.to_f/total_dogs
end
end
Back to your question: #dog.type invokes type method on #dog which returns its instance variable; #dog.popularity invokes popularity method on #dog which does calculations (as defined by you) on the fly and returns the result. No magic here!
I'm using Ruby on Rails. and I have a module called PatientFactory and it will be included in a Patient model.
I need to access a Patient's id, from this module.
module PatientFactory
def self.included(base)
# need to access instance variable here
...
end
end
But more importantly, I need it in the self.included(base)
I can easily access it outside of this method but how do I access it inside?
Given you want to do this:
class Patient < ActiveRecord::Base
include PatientFactory
end
then you would access the id like this:
module PatientFactory
def get_patient_id
self.id
end
end
a = Patient.new
a.id #=> nil
a.save
a.id #=> Integer
when your module gets included it a class, all of its methods become instance methods of that class. if you rather extend them, they get inserted in your class's singleton class, therefore they'll be accessible as if they were class methods.
class Patient < ActiveRecord::Base
include PatientFactory
end
Then you can access the instance as if they were part of Patient's methods.
If you still need to preserve your workflow as you mentioned, Yehuda might offer some help;
http://yehudakatz.com/2009/11/12/better-ruby-idioms/
I have a rails model class
class Model < ActiveRecord::Base
has_many :object_collection
def add_object(object)
object_collection.push object // works
#object_collection.push object // does not work
self.object_collection.push object // works
end
end
I was wondering if someone can please explain to me why the # does not work yet self does i thought these two meant the same
cheers
They are not the same. Consider the following Ruby code:
class Person
attr_accessor :employer
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
The method attr_accessor conveniently generates an attribute reader and writer for you (employer= and employer). You can use these methods to read and write an attribute, which is stored in the instance variable #employer.
Now, we can rewrite the above to the following, which is functionally identical to the code above:
class Person
def employer=(new_employer)
#works_for = new_employer
end
def employer
#works_for
end
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
Now, the instance variable #employer is no longer used. We chose to write the accessors manually, and have the freedom to pick a different name for the instance variable. In this particular example, the name of the instance variable is different than the name of the attribute accessors. There is nothing that prevents you from doing that.
This is similar to how ActiveRecord stores its attributes internally. They are not stored in instance variables of the same name, that is why your push call to #object_collection does not work.
As you may understand, attribute readers and writers offer a certain abstraction that can hide the implementation details from you. Reading and writing instance variables directly in subclasses is therefore generally considered bad practice.
#foo identifies an instance variable called #foo. foo identified a method called foo.
By default, instance variables in Ruby are private. It means you cannot access the value of an instance variable unless you have some public method that exposes the value.
Those methods are called setters and getters. By convenction, setter and getter have the same name of the instance variable, but this is not a requirement.
class MyClass
def initialize
#foo
end
def foo=(value)
#foo = foo
end
def foo
#foo
end
def an_other_foo=(value)
#foo = foo
end
def an_other_foo
#foo
end
end
Though methods and instance variables can have similar names, thery are different elements.
If this topic is not clear to you, you probably need to stop playing with Rails and go back studying how Ruby works.
In your specific case, object_collection doesn't exist as an instance variable because it's an association method.
They do not mean the same thing. One is an instance variable, the other is a method.
The #foo means "the value of the instance variable foo", where as self.foo means "the value of a call to the method foo on myself".
It is typical for a method foo= to set the #foo instance variable, so I can see how someone new to the language might be confused. I'd encourage you to pick up a book on the ruby language. There's one specifically for people who have done some rails but never learned ruby proper. You often can hack rails without understanding the language or what these statements mean, but you'll be far less productive than someone who spends the small amount of time it takes to learn the ruby language itself.
As a general rule, use the self.foo form whenever you can, as this is less sensitive to changes in the classes definition.