The Calm Before the Cast Understanding ActiveRecords Casting
What is Casting?Casting is a manufacturing process by which aliquid material is usually poured into a moldIn computer scie...
ActiveRecords CastingExtending the ActiveRecord::Base classcreates attribute accessors that map to a givendatabase tables ...
ActiveRecords Type CastingSystembundle open activerecordDatabase specific adapters read columndefinitions (extend abstract...
CREATE TABLE foo (                            bar integer,                            baz character varying(255),         ...
What happens when this implicittype casting fails?# == Schema Information# bar :integer# qux :datetimeclass Foo < ActiveRe...
(Obligatory "Cool" picture)
What About Validations?ActiveRecord has some validations, such asIntegers "validates :numericality => true" (isthis even a...
Before the Cast:ActiveRecord provides dynamic methods thathold a value before and after the type cast:a = Foo.new(:bar => ...
Lets Write our Own Validatorclass Foo < ActiveRecord::Base validate :datetime_value_is_castable def datetime_value_is_cast...
And The Exciting Conclusiona = Foo.new(:qux => cheezburger)a.valid? # => falsea.errors # => { :qux => ["is not a valid dat...
Questions/Comments        Ben Simpson    ben@mojotech.com     http://mrfrosti.com          @mrfrosti
Upcoming SlideShare
Loading in …5
×

Active records before_type_cast

3,738 views

Published on

Covers the before_type_cast method provided by ActiveRecord::Base, and when you would want to use it

Published in: Technology
1 Comment
4 Likes
Statistics
Notes
No Downloads
Views
Total views
3,738
On SlideShare
0
From Embeds
0
Number of Embeds
396
Actions
Shares
0
Downloads
6
Comments
1
Likes
4
Embeds 0
No embeds

No notes for slide

Active records before_type_cast

  1. 1. The Calm Before the Cast Understanding ActiveRecords Casting
  2. 2. What is Casting?Casting is a manufacturing process by which aliquid material is usually poured into a moldIn computer science it is the explicit changingof the data type of a given entitye.g, casting a string into an array:Array("foo") # => ["foo"]
  3. 3. ActiveRecords CastingExtending the ActiveRecord::Base classcreates attribute accessors that map to a givendatabase tables columnsThe column type in the database dictates thedata type of the returned valueDatabase data types != Ruby data types
  4. 4. ActiveRecords Type CastingSystembundle open activerecordDatabase specific adapters read columndefinitions (extend abstract):lib/active_record/connection_adapters/postgresql_adapter.rb|74These are cast to Ruby classes:lib/active_record/connection_adapters/abstract/schema_definitions.rb|70
  5. 5. CREATE TABLE foo ( bar integer, baz character varying(255), qux timestamp without time zone ); SELECT * FROM foo WHERE id=1;Casting occurs here { Abstract adapter Postgres adapter Foo.find(1) # => #<Foo bar: 1, baz "a", qux: "2012-03- 06 12:00:00">
  6. 6. What happens when this implicittype casting fails?# == Schema Information# bar :integer# qux :datetimeclass Foo < ActiveRecord::Base; end$ Foo.new(:bar => a, :qux => cheezburger)#<Foo bar: 0, qux: nil>
  7. 7. (Obligatory "Cool" picture)
  8. 8. What About Validations?ActiveRecord has some validations, such asIntegers "validates :numericality => true" (isthis even a real word?!)But not all data types have validations e.g.DateTimeA nil value for datetime after the type cast maysilently pass validation, losing a users inputwithout notice
  9. 9. Before the Cast:ActiveRecord provides dynamic methods thathold a value before and after the type cast:a = Foo.new(:bar => a, :qux => cheezburger)a.qux # nila.qux_before_type_cast # "cheezburger"
  10. 10. Lets Write our Own Validatorclass Foo < ActiveRecord::Base validate :datetime_value_is_castable def datetime_value_is_castable begin DateTime.parse(qux_before_type_cast) rescue ArgumentError errors.add(:qux, "is not a valid date format") end endend
  11. 11. And The Exciting Conclusiona = Foo.new(:qux => cheezburger)a.valid? # => falsea.errors # => { :qux => ["is not a valid dateformat" ]}Now the user can be alerted that their value isinvalid, without it being silently discarded
  12. 12. Questions/Comments Ben Simpson ben@mojotech.com http://mrfrosti.com @mrfrosti

×