Skip to content

Commit

Permalink
Fixed scopes with prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
jthopple committed Aug 24, 2011
1 parent 25d9d5a commit 3a95f08
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 22 deletions.
2 changes: 1 addition & 1 deletion enum_field.gemspec
Expand Up @@ -17,7 +17,7 @@ Gem::Specification.new do |s|
s.add_development_dependency "mocha"
s.add_development_dependency "sqlite3"

s.add_dependency "activerecord", "~> 3.0"
s.add_dependency "activerecord", ">= 3.0.7"

s.files = `git ls-files`.split("\n")
s.require_path = 'lib'
Expand Down
51 changes: 30 additions & 21 deletions lib/enum_field.rb
Expand Up @@ -24,28 +24,17 @@ module EnumField
# - out_of_this_world?
# - define the STATUSES constant, which contains the acceptable values
def enum_field(field, possible_values, options={})
prefix = EnumField.prefix(field, options)
prefix = prefix(field, options)

possible_values.each do |value|
EnumField.check_value(value)
method_name = EnumField.methodize_value(value)

name = "#{prefix}#{method_name}"
const = name.upcase
unless const_defined?(const)
const_set const, value
end

define_method("#{prefix}#{method_name}?") do
self.send(field) == value
end

verify_format(value)
method_name = methodize_value(value, prefix)
define_value_constant(method_name, value)
define_query_method(field, method_name, value)
scope method_name.to_sym, where({ field.to_sym => value })
end

unless const_defined?(field.to_s.pluralize.upcase)
const_set field.to_s.pluralize.upcase, possible_values
end
define_values_constant(field, possible_values)

validates_inclusion_of field,
:in => possible_values,
Expand All @@ -55,19 +44,39 @@ def enum_field(field, possible_values, options={})
end

private
def self.prefix(field, options)
def prefix(field, options)
prefix = options[:prefix]
return nil if prefix == false
prefix && "#{prefix == true ? field : prefix}_"
end

def self.check_value(value)
def verify_format(value)
if value.to_s !~ /^[\w\s_-]*$/
raise ArgumentError.new("Invalid enum value: #{value}")
end
end

def self.methodize_value(value)
value.downcase.gsub(/[-\s]/, '_')
def methodize_value(value, prefix)
"#{prefix}#{value.downcase.gsub(/[-\s]/, '_')}"
end

def define_value_constant(method_name, value)
const = method_name.upcase
unless const_defined?(const)
const_set const, value
end
end

def define_query_method(field, method_name, value)
define_method("#{method_name}?") do
self.send(field) == value
end
end

def define_values_constant(field, values)
unless const_defined?(field.to_s.pluralize.upcase)
const_set field.to_s.pluralize.upcase, values
end
end
end

Expand Down

0 comments on commit 3a95f08

Please sign in to comment.