Sha256: 53f1565edfa775a8a6a9320205f63baa991e0ec697039b6f835c3bb49eb6c9eb

Contents?: true

Size: 1.28 KB

Versions: 9

Compression:

Stored size: 1.28 KB

Contents

require 'facet/hash/keys_to_sym'

class Module
  #
  # Attributing casting is useful in forcing attributes
  # to specified types on read or write access. Though #cast
  # is also quite general, in that any method can be cast via
  # any other method.
  #
  #   require 'facet/module/cast'
  #
  #   class C
  #     attr_accessor :a
  #     cast :a => :to_s
  #   end
  #
  #   c = C.new
  #   c.a = 1
  #   c.a  #=> "1"
  #
  # Other examples:
  #
  #   # simple type casting
  #   cast :a => :to_s
  #
  #   # fancy type casting
  #   cast :a => 'to_s.capitalize'
  #
  #--
  # Planned Funtionality:
  #
  #   # a powerful reader!
  #   cast :a => fn{ |x| eval x }
  #  
  #   # a writer that type checks (using type.rb) (NOT YET FUNCTIONAL)
  #   cast :a= => fn{ |x| big4 x }
  #  
  #   # they can also be grouped (NOT YET FUNCTIONAL)
  #   cast [:x, :y] => :to_s
  #++
  def cast( h )
    h.each { |n,c|
      alias_method( :"-#{n}", n )
      private :"-#{n}"
      case n.to_s[-1,1]
      when '='
        module_eval %{
          def #{n}(x)
            self.send("-#{n}", x.#{c})
          end
        }
      else
        module_eval %{
          def #{n}(*args)
            self.send("-#{n}", *args).#{c}
          end
        }
      end
    }
    made = h.keys_to_sym.keys
    return *made
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
facets-1.4.1 forge/core/module/cast.rb
facets-1.4.2 forge/core/module/cast.rb
facets-1.4.3 forge/core/module/cast.rb
facets-1.4.5 snip/core/module/cast.rb
facets-1.4.4 forge/core/module/cast.rb
facets-1.8.0 work/core/module/cast.rb
facets-1.8.20 work/core/module/cast.rb
facets-1.8.49 work/core/module/cast.rb
facets-1.8.8 work/core/module/cast.rb