Module: CurlyMustache::Attributes::Types
- Defined in:
- lib/curly_mustache/attributes/types.rb
Overview
CurlyMustache
comes with 5 types predefined: string, integer, float, time, boolean. You can redefine any of them or add new type defintions. To define a type is simply to define how a value gets typecasted.
CurlyMustache::Attributes::Types.define(:capitalized_string) do |value|
value.capitalize
end
Now if you have a user class…
class User < CurlyMustache::Base
attribute :name, :string
attribute :title, :capitalized_string
end
And you can see the new type in action…
user = User.new
user.name = "chris"
user.title = "mr"
user.name # => "chris"
user.title # => "Mr"
user.title = 123 # NoMethodError: undefined method `capitalize' for 123:Fixnum
Class Method Summary collapse
-
.[](name) ⇒ Object
Similar to
CurlyMustache::Attributes::Types.defintions[name]
but is indifferent to whethername
is a string or symbol and will raise an exception ifname
is not a defined. -
.clear ⇒ Object
Clear all type defintions (including the defaults).
-
.define(name, &block) ⇒ Object
Define a type.
-
.definitions ⇒ Object
Gets a hash of all type defintions.
Class Method Details
.[](name) ⇒ Object
Similar to CurlyMustache::Attributes::Types.defintions[name]
but is indifferent to whether name
is a string or symbol and will raise an exception if name
is not a defined.
41 42 43 44 45 |
# File 'lib/curly_mustache/attributes/types.rb', line 41 def self.[](name) name = name.to_s raise TypeError, "type #{name} is not defined" unless definitions.has_key?(name) definitions[name] end |
.clear ⇒ Object
Clear all type defintions (including the defaults).
29 30 31 |
# File 'lib/curly_mustache/attributes/types.rb', line 29 def self.clear @definitions = {} end |
.define(name, &block) ⇒ Object
Define a type. The block takes a single argument which is the raw value and should return the typecasted value.
35 36 37 |
# File 'lib/curly_mustache/attributes/types.rb', line 35 def self.define(name, &block) definitions[name.to_s] = OpenStruct.new(:name => name, :caster => block) end |
.definitions ⇒ Object
Gets a hash of all type defintions. The keys will be the type names and they will always be strings.
24 25 26 |
# File 'lib/curly_mustache/attributes/types.rb', line 24 def self.definitions @definitions ||= {} end |