2009-12-20 19:42:16 -05:00
|
|
|
require 'active_resource/exceptions'
|
|
|
|
|
|
|
|
module ActiveResource # :nodoc:
|
2009-12-20 19:44:13 -05:00
|
|
|
class Schema # :nodoc:
|
2009-12-20 19:42:16 -05:00
|
|
|
# attributes can be known to be one of these types. They are easy to
|
|
|
|
# cast to/from.
|
|
|
|
KNOWN_ATTRIBUTE_TYPES = %w( string integer float )
|
|
|
|
|
|
|
|
# An array of attribute definitions, representing the attributes that
|
|
|
|
# have been defined.
|
|
|
|
attr_accessor :attrs
|
|
|
|
|
2009-12-20 19:44:13 -05:00
|
|
|
# The internals of an Active Resource Schema are very simple -
|
2009-12-20 19:42:16 -05:00
|
|
|
# unlike an Active Record TableDefinition (on which it is based).
|
|
|
|
# It provides a set of convenience methods for people to define their
|
|
|
|
# schema using the syntax:
|
2009-12-20 20:03:22 -05:00
|
|
|
# schema do
|
|
|
|
# string :foo
|
|
|
|
# integer :bar
|
2009-12-20 19:42:16 -05:00
|
|
|
# end
|
|
|
|
#
|
|
|
|
# The schema stores the name and type of each attribute. That is then
|
2009-12-20 19:48:01 -05:00
|
|
|
# read out by the schema method to populate the actual
|
2009-12-20 19:42:16 -05:00
|
|
|
# Resource's schema
|
|
|
|
def initialize
|
|
|
|
@attrs = {}
|
|
|
|
end
|
|
|
|
|
|
|
|
def attribute(name, type, options = {})
|
2009-12-20 19:44:13 -05:00
|
|
|
raise ArgumentError, "Unknown Attribute type: #{type.inspect} for key: #{name.inspect}" unless type.nil? || Schema::KNOWN_ATTRIBUTE_TYPES.include?(type.to_s)
|
2009-12-20 19:42:16 -05:00
|
|
|
|
|
|
|
the_type = type.to_s
|
|
|
|
# TODO: add defaults
|
|
|
|
#the_attr = [type.to_s]
|
|
|
|
#the_attr << options[:default] if options.has_key? :default
|
|
|
|
@attrs[name.to_s] = the_type
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
# The following are the attribute types supported by Active Resource
|
2009-12-20 19:44:13 -05:00
|
|
|
# migrations.
|
2009-12-20 19:42:16 -05:00
|
|
|
# TODO: We should eventually support all of these:
|
|
|
|
# %w( string text integer float decimal datetime timestamp time date binary boolean ).each do |attr_type|
|
|
|
|
KNOWN_ATTRIBUTE_TYPES.each do |attr_type|
|
2010-05-14 15:10:10 -04:00
|
|
|
class_eval <<-EOV, __FILE__, __LINE__ + 1
|
2009-12-20 20:03:47 -05:00
|
|
|
def #{attr_type.to_s}(*args)
|
|
|
|
options = args.extract_options!
|
|
|
|
attr_names = args
|
|
|
|
|
|
|
|
attr_names.each { |name| attribute(name, '#{attr_type}', options) }
|
|
|
|
end
|
2009-12-20 19:42:16 -05:00
|
|
|
EOV
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|