Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SmartProperties

t6d
June 05, 2012

 SmartProperties

Ruby accessors on steroids – http://github.com/t6d/smart_properties

t6d

June 05, 2012
Tweet

More Decks by t6d

Other Decks in Programming

Transcript

  1. class Message attr_reader :subject def initialize(attrs = {}) self.subject =

    attrs[:subject] end def subject=(value) unless value raise ArgumentError, "No subject given" end value = value.to_s if value.length < 3 raise ArgumentError, "Invalid subject" end @subject = value end end attr_accessor •Doesn't always do the job •No conversion •No validation •No support for default values •No support for not-nil constraint •Results in tedious work you have to do OVER AND OVER again
  2. require 'smart_properties' class Message include SmartProperties property :subject, :required =>

    true, :converts => :to_s, :accepts => lambda { |s| s.length >= 3 } end SmartProperties •Features •Conversion •Validation •Default values •Not-nil constraint •Simple Interface
  3. require 'smart_properties' class Message include SmartProperties property :subject, :required =>

    true, :converts => :to_s, :accepts => lambda { |s| s.length >= 3 } def subject subject = super # do something amazing … end end SmartProperties •Advanced features •Overriding methods