Your SlideShare is downloading. ×
Active records before_type_cast
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Active records before_type_cast

2,577
views

Published on

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

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

Published in: Technology

1 Comment
2 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,577
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
3
Comments
1
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. The Calm Before the Cast Understanding ActiveRecords Casting
  • 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. 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. 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. 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. 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. (Obligatory "Cool" picture)
  • 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. 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. 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. 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. Questions/Comments Ben Simpson ben@mojotech.com http://mrfrosti.com @mrfrosti