fmt_alias 0.0.1 → 0.0.3
Sign up to get free protection for your applications and to get access to all the features.
- data/Gemfile.lock +1 -1
- data/lib/fmt_alias/aliases.rb +28 -0
- data/lib/fmt_alias/version.rb +1 -1
- data/spec/fmt_alias/fmt_alias_spec.rb +16 -2
- data/spec/spec_helper.rb +5 -0
- metadata +1 -1
data/Gemfile.lock
CHANGED
data/lib/fmt_alias/aliases.rb
CHANGED
@@ -26,6 +26,34 @@ module FmtAlias
|
|
26
26
|
*args
|
27
27
|
)
|
28
28
|
end
|
29
|
+
|
30
|
+
def split_alias(attr, *args)
|
31
|
+
options = args.extract_options!
|
32
|
+
polymorphic = options.delete(:polymorphic)
|
33
|
+
attrs = options.delete(:attrs)
|
34
|
+
delim = options.delete(:delimiter) || ':'
|
35
|
+
raise ArgumentError, "Specify :polymorphic or :attrs option for split_alias :#{attr} in #{self.name}" if attrs.blank? && polymorphic.blank?
|
36
|
+
if polymorphic
|
37
|
+
attrs = ["#{attr}_type", "#{attr}_id"]
|
38
|
+
options[:name] ||= "#{attr}_type_id"
|
39
|
+
else
|
40
|
+
options[:name] ||= "#{attr}_split"
|
41
|
+
end
|
42
|
+
|
43
|
+
define_alias_for(
|
44
|
+
attr,
|
45
|
+
proc {
|
46
|
+
r = attrs.map { |a| send(a) }.compact
|
47
|
+
r.present? ? r.join(delim) : nil
|
48
|
+
},
|
49
|
+
proc { |value|
|
50
|
+
values = value.to_s.split(delim)
|
51
|
+
h = Hash[attrs.zip(values)]
|
52
|
+
h.map { |a, v| send("#{a}=", v) }
|
53
|
+
},
|
54
|
+
options
|
55
|
+
)
|
56
|
+
end
|
29
57
|
end
|
30
58
|
end
|
31
59
|
end
|
data/lib/fmt_alias/version.rb
CHANGED
@@ -34,7 +34,21 @@ describe "Fmt_alias spec" do
|
|
34
34
|
end
|
35
35
|
end
|
36
36
|
|
37
|
-
context "
|
38
|
-
|
37
|
+
context "polymorphic conversions" do
|
38
|
+
it "should correctly convert polymorphic" do
|
39
|
+
@t.poly_type_id = "Page:3"
|
40
|
+
@t.poly_type.should == 'Page'
|
41
|
+
@t.poly_id.should == '3'
|
42
|
+
|
43
|
+
@t.poly_type_id = "Banner:4"
|
44
|
+
@t.poly_type_id.should == "Banner:4"
|
45
|
+
|
46
|
+
@t.poly_type_id = nil
|
47
|
+
@t.poly_type_id.should == nil
|
48
|
+
|
49
|
+
@t.poly_type = nil
|
50
|
+
@t.poly_id = 5
|
51
|
+
@t.poly_type_id.should == "5"
|
52
|
+
end
|
39
53
|
end
|
40
54
|
end
|
data/spec/spec_helper.rb
CHANGED
@@ -15,7 +15,12 @@ $: << File.join(File.dirname(__FILE__), '..', 'lib')
|
|
15
15
|
class TestClass
|
16
16
|
include FmtAlias::Aliases
|
17
17
|
attr_accessor :d, :dt
|
18
|
+
attr_accessor :poly_id, :poly_type
|
19
|
+
attr_accessor :value1, :value2, :value3
|
18
20
|
|
19
21
|
date_fmt_alias(:d, "%Y%m%d")
|
20
22
|
date_fmt_alias(:dt, "%Y%m%d %H:%M")
|
23
|
+
|
24
|
+
split_alias(:poly, :polymorphic => true)
|
25
|
+
split_alias(:values, :attrs => [:value1, :value2, :value3])
|
21
26
|
end
|