enumerations_mixin 0.2.0
Sign up to get free protection for your applications and to get access to all the features.
- data/LICENSE +20 -0
- data/README.md +120 -0
- data/examples/virtual_enumerations_sample.rb +76 -0
- data/lib/active_record/acts/enumerated.rb +176 -0
- data/lib/active_record/aggregations/has_enumerated.rb +60 -0
- data/lib/active_record/virtual_enumerations.rb +68 -0
- data/lib/enumerations_mixin.rb +12 -0
- metadata +90 -0
data/LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright (c) 2005 Trevor Squires
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject
|
9
|
+
to the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
|
18
|
+
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
19
|
+
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,120 @@
|
|
1
|
+
# Enumerations Mixin
|
2
|
+
|
3
|
+
Copyright (c) 2005 Trevor Squires
|
4
|
+
Released under the MIT License. See the LICENSE file for more details.
|
5
|
+
|
6
|
+
## What is this?:
|
7
|
+
|
8
|
+
The enumerations mixin allows you to treat instances of your
|
9
|
+
ActiveRecord models as though they were an enumeration of values.
|
10
|
+
|
11
|
+
This is a modernization for use as a gem on Rails 3 of the original plugin by Trevor Squires
|
12
|
+
located at https://github.com/protocool/enumerations_mixin
|
13
|
+
|
14
|
+
At it's most basic level, it allows you to say things along the lines of:
|
15
|
+
|
16
|
+
booking = Booking.new(:status => BookingStatus[:provisional])
|
17
|
+
booking.update_attribute(:status, BookingStatus[:confirmed])
|
18
|
+
|
19
|
+
Booking.find :first,
|
20
|
+
:conditions => ['status_id = ?', BookingStatus[:provisional].id]
|
21
|
+
|
22
|
+
BookingStatus.all.collect {|status|, [status.name, status.id]}
|
23
|
+
|
24
|
+
See "How to use it" below for more information.
|
25
|
+
|
26
|
+
## Installation
|
27
|
+
|
28
|
+
Simply add the gem to your Gemfile
|
29
|
+
|
30
|
+
gem 'enumerations_mixin'
|
31
|
+
|
32
|
+
## Gem Contents
|
33
|
+
|
34
|
+
This package adds two mixins and a helper to Rails' ActiveRecord:
|
35
|
+
|
36
|
+
<code>acts_as_enumerated</code> provides capabilities to treat your model and its records as an enumeration. At a minimum, the database table for an acts_as_enumerated must contain an 'id' column and a 'name' column. All instances for the acts_as_enumerated model are cached in memory.
|
37
|
+
|
38
|
+
<code>has_enumerated</code> adds methods to your ActiveRecord model for setting and retrieving enumerated values using an associated acts_as_enumerated model.
|
39
|
+
|
40
|
+
There is also an <code>ActiveRecord::VirtualEnumerations</code> helper module to create 'virtual' acts_as_enumerated models which helps to avoid cluttering up your models directory with acts_as_enumerated classes.
|
41
|
+
|
42
|
+
## How to use it
|
43
|
+
|
44
|
+
<code>acts_as_enumerated</code>
|
45
|
+
|
46
|
+
class BookingStatus < ActiveRecord::Base
|
47
|
+
acts_as_enumerated :conditions => 'optional_sql_conditions',
|
48
|
+
:order => 'optional_sql_orderby',
|
49
|
+
:on_lookup_failure => :optional_class_method
|
50
|
+
end
|
51
|
+
|
52
|
+
With that, your BookingStatus class will have the following methods defined:
|
53
|
+
|
54
|
+
<code>BookingStatus[arg]</code>
|
55
|
+
|
56
|
+
Lookup the BookingStatus instance for arg. The arg value can be a 'string' or a :symbol, in which case the lookup will be against the BookingStatus.name field. Alternatively arg can be a Fixnum, in which case the lookup will be against the BookingStatus.id field.
|
57
|
+
|
58
|
+
The <code>:on_lookup_failure</code> option specifies the name of a class method to invoke when the [] method is unable to locate a BookingStatus record for arg. The default is the built-in :enforce_strict_literals which causes an exception to be raised when no record is found and the arg is a Fixnum or Symbol, otherwise it returns nil. There are also built-ins for :enforce_strict (raise and exception regardless of the type for arg) and :enforce_none which just returns nil.
|
59
|
+
|
60
|
+
The whole point of the :on_lookup_failure option is that I'm pretty opinionated that a) if the value can't be looked-up for a :symbol that I've passed, it's probably a typo so I want a *big* hint that something is wrong and b) it's likely that my opinion isn't shared by everyone so it should be configurable.
|
61
|
+
|
62
|
+
<code>BookingStatus.all</code>
|
63
|
+
|
64
|
+
Returns an array of all BookingStatus records that match the :conditions specified in acts_as_enumerated, in the order specified by :order.
|
65
|
+
|
66
|
+
NOTE: acts_as_enumerated records are considered immutable. By default you cannot create/alter/destroy instances because they are cached in memory. Because of Rails' process-based model it is not safe to allow updating acts_as_enumerated records as the caches will get out of sync.
|
67
|
+
|
68
|
+
However, one instance where updating the models *should* be allowed is if you are using ActiveRecord Migrations.
|
69
|
+
|
70
|
+
Using the above example you would do the following:
|
71
|
+
|
72
|
+
BookingStatus.enumeration_model_updates_permitted = true
|
73
|
+
BookingStatus.create(:name => 'newname')
|
74
|
+
|
75
|
+
<code>has_enumerated</code>
|
76
|
+
|
77
|
+
First of all, note that you *could* specify the relationship to an acts_as_enumerated class using the belongs_to association. However, has_enumerated is preferable because you aren't really associated to the enumerated value, you are *aggregating* it. As such, the has_enumerated macro behaves more like an aggregation than an association.
|
78
|
+
|
79
|
+
class Booking < ActiveRecord::Base
|
80
|
+
has_enumerated :status, :class_name => 'BookingStatus',
|
81
|
+
:foreign_key => 'status_id',
|
82
|
+
:on_lookup_failure => :optional_instance_method
|
83
|
+
end
|
84
|
+
|
85
|
+
By default, the foreign key is interpreted to be the name of your has_enumerated field (in this case 'status') plus '_id'. Additionally, the default value for :class_name is the camel-ized version of the name for your has_enumerated field. :on_lookup_failure is explained below.
|
86
|
+
|
87
|
+
With that, your Booking class will have the following methods defined:
|
88
|
+
|
89
|
+
<code>status</code>
|
90
|
+
|
91
|
+
Returns the BookingStatus with an id that matches the value in the Booking.status_id.
|
92
|
+
|
93
|
+
<code>status=</code>
|
94
|
+
|
95
|
+
Sets the value for Booking.status_id using the id of the BookingStatus instance passed as an argument. As a short-hand,
|
96
|
+
you can also pass it the 'name' of a BookingStatus instance, either as a 'string' or :symbol.
|
97
|
+
|
98
|
+
example:
|
99
|
+
|
100
|
+
mybooking.status = :confirmed or mybooking.update_attribute(:status, :confirmed)
|
101
|
+
|
102
|
+
The <code>:on_lookup_failure</code> option in has_enumerated is there because (again) I'm opinionated about what should happen. By default, if booking.status_id contains an id that isn't a valid <code>BookingStatus.id</code> I just want booking.status to return nil rather than throw an exception. This ensures I can edit my Booking instances without having to put rescue blocks around all my booking.status calls. However, if I call <code>booking.status = :bogus</code> I want noisy hints about the bug.
|
103
|
+
|
104
|
+
Of course, you may not agree with that in which case you can specify an *instance* method to be called in the case of a lookup failure. The method signature is as follows:
|
105
|
+
|
106
|
+
your_lookup_handler(operation, name, name_foreign_key, acts_enumerated_class_name, lookup_value)
|
107
|
+
|
108
|
+
The 'operation' arg will be either :read or :write. In the case of :read you are expected to return something or raise an exception, while in the case of a :write you don't have to return anything.
|
109
|
+
|
110
|
+
Note that there's enough information in the method signature that you can specify one method to handle all lookup failures for all has_enumerated fields if you happen to have more than one defined in your model.
|
111
|
+
|
112
|
+
<code>ActiveRecord::VirtualEnumerations</code>
|
113
|
+
|
114
|
+
For the most part, your acts_as_enumerated classes will do nothing more than just act as enumerated.
|
115
|
+
|
116
|
+
In that case there isn't much point cluttering up your models directory with those class files. You can use ActiveRecord::VirtualEnumerations to reduce that clutter.
|
117
|
+
|
118
|
+
Copy virtual_enumerations_sample.rb to Rails.root/config/initializers/virtual_enumerations.rb and configure it accordingly.
|
119
|
+
|
120
|
+
See virtual_enumerations_sample.rb in the examples directory of this gem for a full description.
|
@@ -0,0 +1,76 @@
|
|
1
|
+
# Copyright (c) 2005 Trevor Squires
|
2
|
+
# Released under the MIT License. See the LICENSE file for more details.
|
3
|
+
|
4
|
+
# Copy this file to Rails.root/config/initializers/virtual_enumerations.rb
|
5
|
+
# and configure it accordingly.
|
6
|
+
ActiveRecord::VirtualEnumerations.define do |config|
|
7
|
+
###
|
8
|
+
# USAGE (and don't worry, it doesn't have to be as ugly as this):
|
9
|
+
# config.define 'ClassName',
|
10
|
+
# :table_name => 'table', :extends => 'SuperclassName',
|
11
|
+
# :conditions => ['something = ?', "value"], :order => 'column ASC',
|
12
|
+
# :on_lookup_failure => :enforce_strict_literals do
|
13
|
+
# class_evaled_functions
|
14
|
+
# end
|
15
|
+
#
|
16
|
+
# 'ClassName', :table_name and :extends are used to define your virtual class.
|
17
|
+
# Note that 'ClassName' can be a :symbol or a 'CamelString'.
|
18
|
+
#
|
19
|
+
# The :conditions, :order and :on_lookup_failure arguments are passed to
|
20
|
+
# acts_as_enumerated in your virtual class. See README_ENUMERATIONS for info
|
21
|
+
# on how acts_as_enumerated works.
|
22
|
+
#
|
23
|
+
# The 'do' block will be class_eval'd by your virtual class after it has
|
24
|
+
# been loaded-on-demand.
|
25
|
+
#
|
26
|
+
###
|
27
|
+
# Okay, that's pretty long-winded.
|
28
|
+
# Everything after the initial 'class_name' is optional so for most applications, this
|
29
|
+
# is about as verbose as you're likely to get:
|
30
|
+
#
|
31
|
+
# config.define :booking_status, :order => 'position ASC'
|
32
|
+
#
|
33
|
+
# In the above example, ActiveRecord assumes the table will be called 'booking_statuses'
|
34
|
+
# and the table should have a 'position' column defined.
|
35
|
+
#
|
36
|
+
# If you've got a bunch of enumeration classes that share the same optional parameters
|
37
|
+
# you can pass an array of names as the first argument, saving your fingers from typing
|
38
|
+
# config.define over and over again:
|
39
|
+
#
|
40
|
+
# config.define [:booking_status, :card_issuer], :order => 'position ASC'
|
41
|
+
#
|
42
|
+
# You can also take advantage of ActiveRecord's STI:
|
43
|
+
#
|
44
|
+
# config.define :enum_record, :order => 'position ASC', :table_name => 'enumrecords'
|
45
|
+
# config.define [:booking_status, :card_issuer], :extends => 'EnumRecord'
|
46
|
+
#
|
47
|
+
# In the above example, all of the records are stored in the table called 'enumrecords'
|
48
|
+
# and all acts_as_enumerated parameters are automatically inherited by the
|
49
|
+
# subclasses (although you can override them if you want).
|
50
|
+
# You can also use :extends to extend a non-virtual model class (that's already in
|
51
|
+
# your models directory) if that floats your boat.
|
52
|
+
#
|
53
|
+
# Finally, that strange optional 'do' block.
|
54
|
+
# You may be struck by the need to tamper with your virtual enumeration class after
|
55
|
+
# it has been loaded-on-demand. This can be as simple as blessing it with a
|
56
|
+
# certain 'act':
|
57
|
+
#
|
58
|
+
# config.define :enum_record, :order => 'position ASC' do
|
59
|
+
# acts_as_list # but see README_ENUMERATIONS for rules about modifying your records
|
60
|
+
# end
|
61
|
+
#
|
62
|
+
# or you may be experimenting with the dark-side... singleton methods
|
63
|
+
#
|
64
|
+
# config.define :card_issuer do
|
65
|
+
# class << self[:visa]; def verify_number(arg); some_code_here; end; end
|
66
|
+
# class << self[:master_card]; def verify_number(arg); some_other_code_here; end; end
|
67
|
+
# end
|
68
|
+
#
|
69
|
+
# For virtual enumerations, this sort of tampering *has* to be defined in the
|
70
|
+
# config.define do block. This is because in development mode, rails loads and
|
71
|
+
# subsequently clobbers your model classes for each request. The 'do' block will
|
72
|
+
# be evaluated each time your model class is loaded-on-demand.
|
73
|
+
#
|
74
|
+
###
|
75
|
+
|
76
|
+
end
|
@@ -0,0 +1,176 @@
|
|
1
|
+
# Copyright (c) 2005 Trevor Squires
|
2
|
+
# Released under the MIT License. See the LICENSE file for more details.
|
3
|
+
|
4
|
+
module ActiveRecord
|
5
|
+
module Acts
|
6
|
+
module Enumerated
|
7
|
+
def self.append_features(base)
|
8
|
+
super
|
9
|
+
base.extend(MacroMethods)
|
10
|
+
end
|
11
|
+
|
12
|
+
module MacroMethods
|
13
|
+
def acts_as_enumerated(options = {})
|
14
|
+
valid_keys = [:conditions, :order, :on_lookup_failure]
|
15
|
+
options.assert_valid_keys(*valid_keys)
|
16
|
+
valid_keys.each do |key|
|
17
|
+
write_inheritable_attribute("acts_enumerated_#{key.to_s}".to_sym, options[key]) if options.has_key? key
|
18
|
+
end
|
19
|
+
|
20
|
+
unless self.is_a? ActiveRecord::Acts::Enumerated::ClassMethods
|
21
|
+
extend ActiveRecord::Acts::Enumerated::ClassMethods
|
22
|
+
class_eval do
|
23
|
+
include ActiveRecord::Acts::Enumerated::InstanceMethods
|
24
|
+
validates_uniqueness_of :name
|
25
|
+
before_save :enumeration_model_update
|
26
|
+
before_destroy :enumeration_model_update
|
27
|
+
end
|
28
|
+
end
|
29
|
+
end
|
30
|
+
end
|
31
|
+
|
32
|
+
module ClassMethods
|
33
|
+
attr_accessor :enumeration_model_updates_permitted
|
34
|
+
|
35
|
+
def all
|
36
|
+
return @all if @all
|
37
|
+
@all = find(:all,
|
38
|
+
:conditions => read_inheritable_attribute(:acts_enumerated_conditions),
|
39
|
+
:order => read_inheritable_attribute(:acts_enumerated_order)
|
40
|
+
).collect{|val| val.freeze}.freeze
|
41
|
+
end
|
42
|
+
|
43
|
+
def [](arg)
|
44
|
+
case arg
|
45
|
+
when Symbol
|
46
|
+
rval = lookup_name(arg.id2name) and return rval
|
47
|
+
when String
|
48
|
+
rval = lookup_name(arg) and return rval
|
49
|
+
when Fixnum
|
50
|
+
rval = lookup_id(arg) and return rval
|
51
|
+
when nil
|
52
|
+
rval = nil
|
53
|
+
else
|
54
|
+
raise TypeError, "#{self.name}[]: argument should be a String, Symbol or Fixnum but got a: #{arg.class.name}"
|
55
|
+
end
|
56
|
+
self.send((read_inheritable_attribute(:acts_enumerated_on_lookup_failure) || :enforce_strict_literals), arg)
|
57
|
+
end
|
58
|
+
|
59
|
+
def lookup_id(arg)
|
60
|
+
all_by_id[arg]
|
61
|
+
end
|
62
|
+
|
63
|
+
def lookup_name(arg)
|
64
|
+
all_by_name[arg]
|
65
|
+
end
|
66
|
+
|
67
|
+
def include?(arg)
|
68
|
+
case arg
|
69
|
+
when Symbol
|
70
|
+
return !lookup_name(arg.id2name).nil?
|
71
|
+
when String
|
72
|
+
return !lookup_name(arg).nil?
|
73
|
+
when Fixnum
|
74
|
+
return !lookup_id(arg).nil?
|
75
|
+
when self
|
76
|
+
possible_match = lookup_id(arg.id)
|
77
|
+
return !possible_match.nil? && possible_match == arg
|
78
|
+
end
|
79
|
+
return false
|
80
|
+
end
|
81
|
+
|
82
|
+
# NOTE: purging the cache is sort of pointless because
|
83
|
+
# of the per-process rails model.
|
84
|
+
# By default this blows up noisily just in case you try to be more
|
85
|
+
# clever than rails allows.
|
86
|
+
# For those times (like in Migrations) when you really do want to
|
87
|
+
# alter the records you can silence the carping by setting
|
88
|
+
# enumeration_model_updates_permitted to true.
|
89
|
+
def purge_enumerations_cache
|
90
|
+
unless self.enumeration_model_updates_permitted
|
91
|
+
raise "#{self.name}: cache purging disabled for your protection"
|
92
|
+
end
|
93
|
+
@all = @all_by_name = @all_by_id = nil
|
94
|
+
end
|
95
|
+
|
96
|
+
private
|
97
|
+
|
98
|
+
def all_by_id
|
99
|
+
return @all_by_id if @all_by_id
|
100
|
+
@all_by_id = all.inject({}) { |memo, item| memo[item.id] = item; memo;}.freeze
|
101
|
+
end
|
102
|
+
|
103
|
+
def all_by_name
|
104
|
+
return @all_by_name if @all_by_name
|
105
|
+
begin
|
106
|
+
@all_by_name = all.inject({}) { |memo, item| memo[item.name] = item; memo;}.freeze
|
107
|
+
rescue NoMethodError => err
|
108
|
+
if err.name == :name
|
109
|
+
raise TypeError, "#{self.name}: you need to define a 'name' column in the table '#{table_name}'"
|
110
|
+
end
|
111
|
+
raise
|
112
|
+
end
|
113
|
+
end
|
114
|
+
|
115
|
+
def enforce_none(arg)
|
116
|
+
return nil
|
117
|
+
end
|
118
|
+
|
119
|
+
def enforce_strict(arg)
|
120
|
+
raise ActiveRecord::RecordNotFound, "Couldn't find a #{self.name} identified by (#{arg.inspect})"
|
121
|
+
end
|
122
|
+
|
123
|
+
def enforce_strict_literals(arg)
|
124
|
+
if Fixnum === arg || Symbol === arg
|
125
|
+
raise ActiveRecord::RecordNotFound, "Couldn't find a #{self.name} identified by (#{arg.inspect})"
|
126
|
+
end
|
127
|
+
return nil
|
128
|
+
end
|
129
|
+
|
130
|
+
end
|
131
|
+
|
132
|
+
module InstanceMethods
|
133
|
+
def ===(arg)
|
134
|
+
case arg
|
135
|
+
when Symbol, String, Fixnum, nil
|
136
|
+
return self == self.class[arg]
|
137
|
+
when Array
|
138
|
+
return self.in?(*arg)
|
139
|
+
end
|
140
|
+
super
|
141
|
+
end
|
142
|
+
|
143
|
+
alias_method :like?, :===
|
144
|
+
|
145
|
+
def in?(*list)
|
146
|
+
for item in list
|
147
|
+
self === item and return true
|
148
|
+
end
|
149
|
+
return false
|
150
|
+
end
|
151
|
+
|
152
|
+
def name_sym
|
153
|
+
self.name.to_sym
|
154
|
+
end
|
155
|
+
|
156
|
+
private
|
157
|
+
|
158
|
+
# NOTE: updating the models that back an acts_as_enumerated is
|
159
|
+
# rather dangerous because of rails' per-process model.
|
160
|
+
# The cached values could get out of synch between processes
|
161
|
+
# and rather than completely disallow changes I make you jump
|
162
|
+
# through an extra hoop just in case you're defining your enumeration
|
163
|
+
# values in Migrations. I.e. set enumeration_model_updates_permitted = true
|
164
|
+
def enumeration_model_update
|
165
|
+
if self.class.enumeration_model_updates_permitted
|
166
|
+
self.class.purge_enumerations_cache
|
167
|
+
return true
|
168
|
+
end
|
169
|
+
# Ugh. This just seems hack-ish. I wonder if there's a better way.
|
170
|
+
self.errors.add('name', "changes to acts_as_enumeration model instances are not permitted")
|
171
|
+
return false
|
172
|
+
end
|
173
|
+
end
|
174
|
+
end
|
175
|
+
end
|
176
|
+
end
|
@@ -0,0 +1,60 @@
|
|
1
|
+
# Copyright (c) 2005 Trevor Squires
|
2
|
+
# Released under the MIT License. See the LICENSE file for more details.
|
3
|
+
|
4
|
+
module ActiveRecord
|
5
|
+
module Aggregations # :nodoc:
|
6
|
+
module HasEnumerated # :nodoc:
|
7
|
+
def self.append_features(base)
|
8
|
+
super
|
9
|
+
base.extend(MacroMethods)
|
10
|
+
end
|
11
|
+
|
12
|
+
module MacroMethods
|
13
|
+
def has_enumerated(part_id, options = {})
|
14
|
+
options.assert_valid_keys(:class_name, :foreign_key, :on_lookup_failure)
|
15
|
+
|
16
|
+
name = part_id.id2name
|
17
|
+
class_name = (options[:class_name] || name).to_s.camelize
|
18
|
+
foreign_key = (options[:foreign_key] || "#{name}_id").to_s
|
19
|
+
failure = options[:on_lookup_failure]
|
20
|
+
|
21
|
+
module_eval <<-end_eval
|
22
|
+
def #{name}
|
23
|
+
rval = #{class_name}.lookup_id(self.#{foreign_key})
|
24
|
+
if rval.nil? && #{!failure.nil?}
|
25
|
+
return self.send(#{failure.inspect}, :read, #{name.inspect}, #{foreign_key.inspect}, #{class_name.inspect}, self.#{foreign_key})
|
26
|
+
end
|
27
|
+
return rval
|
28
|
+
end
|
29
|
+
|
30
|
+
def #{name}=(arg)
|
31
|
+
case arg
|
32
|
+
when #{class_name}
|
33
|
+
val = #{class_name}.lookup_id(arg.id)
|
34
|
+
when String
|
35
|
+
val = #{class_name}.lookup_name(arg)
|
36
|
+
when Symbol
|
37
|
+
val = #{class_name}.lookup_name(arg.id2name)
|
38
|
+
when Fixnum
|
39
|
+
val = #{class_name}.lookup_id(arg)
|
40
|
+
when nil
|
41
|
+
val = nil
|
42
|
+
else
|
43
|
+
raise TypeError, "#{self.name}: #{name}= argument must be a #{class_name}, String, Symbol or Fixnum but got a: \#{arg.class.name}"
|
44
|
+
end
|
45
|
+
|
46
|
+
if val.nil?
|
47
|
+
if #{failure.nil?}
|
48
|
+
raise ArgumentError, "#{self.name}: #{name}= can't assign a #{class_name} for a value of (\#{arg.inspect})"
|
49
|
+
end
|
50
|
+
self.send(#{failure.inspect}, :write, #{name.inspect}, #{foreign_key.inspect}, #{class_name.inspect}, arg)
|
51
|
+
else
|
52
|
+
self.#{foreign_key} = val.id
|
53
|
+
end
|
54
|
+
end
|
55
|
+
end_eval
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
59
|
+
end
|
60
|
+
end
|
@@ -0,0 +1,68 @@
|
|
1
|
+
# Copyright (c) 2005 Trevor Squires
|
2
|
+
# Released under the MIT License. See the LICENSE file for more details.
|
3
|
+
|
4
|
+
module ActiveRecord
|
5
|
+
module VirtualEnumerations # :nodoc:
|
6
|
+
class << self
|
7
|
+
def define
|
8
|
+
raise ArgumentError, "#{self.name}: must pass a block to define()" unless block_given?
|
9
|
+
config = ActiveRecord::VirtualEnumerations::Config.new
|
10
|
+
yield config
|
11
|
+
@config = config # we only overwrite config if no exceptions were thrown
|
12
|
+
end
|
13
|
+
|
14
|
+
def synthesize_if_defined(const)
|
15
|
+
options = @config[const]
|
16
|
+
return nil unless options
|
17
|
+
class_def = <<-end_eval
|
18
|
+
class #{const} < #{options[:extends]}
|
19
|
+
acts_as_enumerated :conditions => #{options[:conditions].inspect},
|
20
|
+
:order => #{options[:order].inspect},
|
21
|
+
:on_lookup_failure => #{options[:on_lookup_failure].inspect}
|
22
|
+
set_table_name(#{options[:table_name].inspect}) unless #{options[:table_name].nil?}
|
23
|
+
end
|
24
|
+
end_eval
|
25
|
+
eval(class_def, TOPLEVEL_BINDING)
|
26
|
+
rval = const_get(const)
|
27
|
+
if options[:post_synth_block]
|
28
|
+
rval.class_eval(&options[:post_synth_block])
|
29
|
+
end
|
30
|
+
return rval
|
31
|
+
end
|
32
|
+
end
|
33
|
+
|
34
|
+
class Config
|
35
|
+
def initialize
|
36
|
+
@enumeration_defs = {}
|
37
|
+
end
|
38
|
+
|
39
|
+
def define(arg, options = {}, &synth_block)
|
40
|
+
(arg.is_a?(Array) ? arg : [arg]).each do |class_name|
|
41
|
+
camel_name = class_name.to_s.camelize
|
42
|
+
raise ArgumentError, "ActiveRecord::VirtualEnumerations.define - invalid class_name argument (#{class_name.inspect})" if camel_name.blank?
|
43
|
+
raise ArgumentError, "ActiveRecord::VirtualEnumerations.define - class_name already defined (#{camel_name})" if @enumeration_defs[camel_name.to_sym]
|
44
|
+
options.assert_valid_keys(:table_name, :extends, :conditions, :order, :on_lookup_failure)
|
45
|
+
enum_def = options.clone
|
46
|
+
enum_def[:extends] ||= "ActiveRecord::Base"
|
47
|
+
enum_def[:post_synth_block] = synth_block
|
48
|
+
@enumeration_defs[camel_name.to_sym] = enum_def
|
49
|
+
end
|
50
|
+
end
|
51
|
+
|
52
|
+
def [](arg)
|
53
|
+
@enumeration_defs[arg]
|
54
|
+
end
|
55
|
+
end #class Config
|
56
|
+
end #module VirtualEnumerations
|
57
|
+
end #module ActiveRecord
|
58
|
+
|
59
|
+
class Module # :nodoc:
|
60
|
+
alias_method :enumerations_original_const_missing, :const_missing
|
61
|
+
def const_missing(const_id)
|
62
|
+
# let rails have a go at loading it
|
63
|
+
enumerations_original_const_missing(const_id)
|
64
|
+
rescue NameError
|
65
|
+
# now it's our turn
|
66
|
+
ActiveRecord::VirtualEnumerations.synthesize_if_defined(const_id) or raise
|
67
|
+
end
|
68
|
+
end
|
@@ -0,0 +1,12 @@
|
|
1
|
+
require "rails"
|
2
|
+
|
3
|
+
class EnumerationsMixin < Rails::Railtie
|
4
|
+
config.autoload_paths << File.expand_path(File.join(__FILE__, "../"))
|
5
|
+
|
6
|
+
initializer 'enumerations_mixin' do
|
7
|
+
ActiveSupport.on_load(:active_record) do
|
8
|
+
include ActiveRecord::Acts::Enumerated
|
9
|
+
include ActiveRecord::Aggregations::HasEnumerated
|
10
|
+
end
|
11
|
+
end
|
12
|
+
end
|
metadata
ADDED
@@ -0,0 +1,90 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: enumerations_mixin
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
hash: 23
|
5
|
+
prerelease: false
|
6
|
+
segments:
|
7
|
+
- 0
|
8
|
+
- 2
|
9
|
+
- 0
|
10
|
+
version: 0.2.0
|
11
|
+
platform: ruby
|
12
|
+
authors:
|
13
|
+
- Trevor Squires
|
14
|
+
- Pivotal Labs
|
15
|
+
autorequire:
|
16
|
+
bindir: bin
|
17
|
+
cert_chain: []
|
18
|
+
|
19
|
+
date: 2010-11-12 00:00:00 +08:00
|
20
|
+
default_executable:
|
21
|
+
dependencies:
|
22
|
+
- !ruby/object:Gem::Dependency
|
23
|
+
name: rails
|
24
|
+
prerelease: false
|
25
|
+
requirement: &id001 !ruby/object:Gem::Requirement
|
26
|
+
none: false
|
27
|
+
requirements:
|
28
|
+
- - ~>
|
29
|
+
- !ruby/object:Gem::Version
|
30
|
+
hash: 7
|
31
|
+
segments:
|
32
|
+
- 3
|
33
|
+
- 0
|
34
|
+
- 0
|
35
|
+
version: 3.0.0
|
36
|
+
type: :runtime
|
37
|
+
version_requirements: *id001
|
38
|
+
description: Allows you to treat instances of your ActiveRecord models as though they were an enumeration of values
|
39
|
+
email: pivotal-opensource@googlegroups.com
|
40
|
+
executables: []
|
41
|
+
|
42
|
+
extensions: []
|
43
|
+
|
44
|
+
extra_rdoc_files:
|
45
|
+
- LICENSE
|
46
|
+
- README.md
|
47
|
+
files:
|
48
|
+
- examples/virtual_enumerations_sample.rb
|
49
|
+
- lib/active_record/acts/enumerated.rb
|
50
|
+
- lib/active_record/aggregations/has_enumerated.rb
|
51
|
+
- lib/active_record/virtual_enumerations.rb
|
52
|
+
- lib/enumerations_mixin.rb
|
53
|
+
- LICENSE
|
54
|
+
- README.md
|
55
|
+
has_rdoc: true
|
56
|
+
homepage: http://github.com/pivotal/enumerations_mixin
|
57
|
+
licenses: []
|
58
|
+
|
59
|
+
post_install_message:
|
60
|
+
rdoc_options:
|
61
|
+
- --charset=UTF-8
|
62
|
+
require_paths:
|
63
|
+
- lib
|
64
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
65
|
+
none: false
|
66
|
+
requirements:
|
67
|
+
- - ">="
|
68
|
+
- !ruby/object:Gem::Version
|
69
|
+
hash: 3
|
70
|
+
segments:
|
71
|
+
- 0
|
72
|
+
version: "0"
|
73
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
74
|
+
none: false
|
75
|
+
requirements:
|
76
|
+
- - ">="
|
77
|
+
- !ruby/object:Gem::Version
|
78
|
+
hash: 3
|
79
|
+
segments:
|
80
|
+
- 0
|
81
|
+
version: "0"
|
82
|
+
requirements: []
|
83
|
+
|
84
|
+
rubyforge_project:
|
85
|
+
rubygems_version: 1.3.7
|
86
|
+
signing_key:
|
87
|
+
specification_version: 3
|
88
|
+
summary: Allows you to treat instances of your ActiveRecord models as though they were an enumeration of values
|
89
|
+
test_files:
|
90
|
+
- examples/virtual_enumerations_sample.rb
|