ActiveRecord::Base::serialize automatically unserializes for some fields - ruby-on-rails

I am serializing two nearly-identical fields on a single model, and when I call the accessor method for one of them, I get the deserialized object, but when I call the accessor method for the other one, I get the ActiveRecord::AttributeMethods::Serialization::Attribute struct.
The difference I see is that for the first field, I declare serialize in an included block of a mixin Module; for the second field, I declare serialize in the class declaration (as normal).
What's causing this? How can I bring the behavior of these two fields into uniformity?
Rails 3.2.13

I found the solution. I moved the problematic serialize declaration (the one which did not produce an automatically-deserializing accessor method) upward a couple of lines so that it appeared above my attr_encrypted declarations.

Related

Instantiating a class by String name in Dart

I am trying to call a method of a class that I only know by name as a String. Now therefore I would need a ClassMirror of that class that allowes me to instantiate an instance. However, creating ClassMirrors seems to be only possible by entering a type using reflectClass(Type) or by passing an already existing instance of that class into reflect(dynamic). So these aren`t helping if I only have a String.
In Java you can do this pretty easily, by calling Class.forName(String). Then you would get a Constructor instance, make it accessibly and call it.
Does anyone know if this is even possible in dart? What seems weird is that once you have a ClassMirror you can access fields and methods by passing symbols, which can be created by Strings.
You can put a specific list of strings to map to a specific list of closures to create a new object with specific parameters.
But you can't get a reflection without using dart:mirrors, which is being deprecated, and also had a negative impact on tree shaking to get the payload size down.
In general, you're invited to look at the package:reflectable to achieve most of what you'd want out of dart:mirrors, using source-to-source builders.

What's mean colon inside a dart class?

I'm trying understand what's the mean of this two final lines of code, on colons... It's a syntax question.
I'm following this github example and I have this doubt on my head.
Can someone help me with this?.
class DietPlan extends ParseObject implements ParseCloneable {
DietPlan() : super(keyDietPlan);
DietPlan.clone() : this();
The part after : is called "initializer list.
It is a list of expressions that can access constructor parameters and can assign to instance fields, even final instance fields.
The first colon, i.e. DietPlan() : super(keyDietPlan); means that you are calling the super constructor, constructor of ParseCloneable in this case.
This is a core OOP concept, you can extend or implement one class to another and you must call the superclass constructor if you do so. This is just a style of doing the same in Dart.
The second colon works in similar way, to understand that you need to understand what is cloning of objects,
Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
This is whats happening on the second line.

Declaring handler and handling errors with a similar approach to after_save

I'm looking to record errors from a handful of objects into a db table, let's say "errs".
Ideally I'd like to declare it so as it can be added to the object definition ins a similar manner to "validate" or "attr_accessible". For example:
def SomeObject
validate: :someMember
on_error: :someCallback
def someMethod
end
end
Where would I begin implementing something of this nature or alternatively is there a commonly accepted method for doing this type of thing?
To expand a bit:
Say I parse a file whose contents define an ActiveRecord extension (ActiveRecord::MyClass) and one of the following errors occur.
1. Type mismatch: self.someMember is STRING, expected BOOLEAN.
2. File badly formatted. Some line isn't formatted as expected.
3. Validation failed (ActiveRecord)
On these errors I'd like to record these using the directive type syntax that is found (typically) at the top of an object definition.
It sounds like you are looking for an Observer. Make an observer for your class, then use the after_validation active record callback to run the code that records your errors.

Ruby instance variables versus ActiveRecord attributes

I've read that ruby objects are just places where we can store instance variables (and class pointers). So:
class Person
def initialize(age)
#age = age
end
end
Now if we run:
p = Person.new(101)
Then we get:
#<Person:0x86cf5b8 #age=101>
Great, the property age is stored as an instance variable, as expected. But things work a little differently if we convert the model to inherit from ActiveRecord. Now, after instantiating an new Person, we see this:
# timestamps removed
#<Person id: 1, age: 101 >
The age property no longer appears to be an instance variable. So what is really going on here?
I know that we can access the #attributes instance variable, which contains a hash of all the properties and values, so I'm wondering if ActiveRecord is possibly modifying the console output to present the objects attributes in this way.
Is it possible to instantiate a Ruby object where properties are held as attributes and not instance variables, without using ActiveRecord?
Yes, you can extend a ruby class with include ActiveModel::AttributeMethods to expose your instance variables as ActiveModel-like attributes.
See the docs for more information.
as you see in your code 'storing' properties as instance vars was your own doing, so if you wanna hold them any other way, is also up to you. ruby gives you convenience class methods to define getter and setter methods like attr_accessor.
also worth noting, that if you inherit from ActiveRecord::Base, you should not override initialize.
I'm wondering if ActiveRecord is possibly modifying the console output to present the objects attributes in this way.
Well, kind of. The method responsible for that is inspect, and it's implemented by Object in a way that (emplasis mine):
...shows the object's class name, an encoding of the object id, and a list of the instance variables and their values (by calling inspect on each of them).
There's more right after:
User defined classes should override this method to provide a better representation of obj.
This is exactly what ActiveRecord does and the reason why you're seeing this output. The overridden method does not list instance variables, but displays AR attributes.
So just because you aren't seeing the instance variable in the console doesn't mean it isn't there!

What type of language construct is Rails' "validates"?

I'm just starting to grok Ruby. My background is in .NET and PHP. In Rails, and I'm sure in other frameworks as well, I see stuff like this on classes:
class Person < ActiveRecord::Base
validates :terms_of_service, :acceptance => true
end
What exactly is "validates"? Is it a function? If it's a function, how does the validation actually work since you don't tell the validates function which model you are validating?
Where can I read more about how this actually works behind the scenes?
It's... a little complicated - but the short answer is that validates is a class method of Person, inherited from ActiveRecord::Base. That line could equally have been written validates(:terms_of_service, :acceptance => true).
Ruby, like a lot of interpreted languages, effectively "executes" class definitions, so when it encounters the validates line, it sees it as a method call where the current self object is the instance of the Class class representing the class Person, inheriting from ActiveRecord::Base. It calls the method, which has the effect of hooking a validator into the Person class.
You can read about the method here - but do note that that adds more confusion, since it lists the method as an instance method of ActiveModel::Validations::ClassMethods. Huh? Well, Ruby has two ways of taking functionality from another Module and putting it into your class - you can either include the module (in which case its instance methods become instance methods of your class), or extend the module (in which case its instance methods become class methods of your class).
So, to summarise: validates is declared as an instance method of ActiveModel::Validations::ClassMethods, which is extended into ActiveRecord::Base. Therefore, validates is a class method of ActiveRecord::Base and, by inheritance, Person. The line in your code snippet is just a method call.
However, having said all that, most Rubyists and Railsists will largely ignore those facts; validates is what's called a "decorator", and most people will simply read it as a statement about Person.
It's a special callback method that gets called to validate data before it's saved to the database.
A callback, more generally, is a method that "hooks into" an object or code module/library in such a way that the method gets called automatically when certain events occur. In this case, the event that calls the set of validation methods is the act of trying to save something to the database. This is useful because, before you write new or updated information to your database, you want to make sure it's valid, in order to prevent bad data from leaking into your application.
The following methods trigger validations, and will save the object to the database only if all validations pass (in the literal sense, this means all the validation methods must return a value that is not false, or nil, etc., otherwise validation is considered to have failed):
create
create!
save
save!
update
update_attributes
update_attributes!
"Methods" in Ruby are very similar to the concept of functions in other languages. In many cases you can think of them interchangeably - they declare some functionality, they take parameters as input, and they return a result as output.
More detail on validations: http://guides.rubyonrails.org/active_record_validations_callbacks.html
Ruby (and Rails) use "callbacks" in many different situations - pretty much anytime you want some method to be called as a result of some event occuring.
More reading on callbacks: http://www.khelll.com/blog/ruby/ruby-callbacks/

Resources