Skip to content

Commit e4ef7e7

Browse files
committed
Merge pull request #145 from matugm/patch-1
Improve Attribute#from_model
2 parents 6e64c49 + 2e221e0 commit e4ef7e7

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

lib/rails_erd/domain/attribute.rb

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,18 @@ def from_model(domain, model) # @private :nodoc:
1414
attributes.sort! if RailsERD.options[:sort]
1515

1616
if RailsERD.options[:prepend_primary]
17-
primary_key = ActiveRecord::Base.get_primary_key(model)
18-
primary = attributes.detect{ |column| column.name == primary_key }
17+
attributes = prepend_primary(model, attributes)
18+
end
19+
20+
attributes
21+
end
22+
23+
def prepend_primary(model, attributes)
24+
primary_key = ActiveRecord::Base.get_primary_key(model)
25+
primary = attributes.index { |column| column.name == primary_key }
1926

20-
if primary
21-
attributes.delete(primary)
22-
attributes.unshift(primary)
23-
end
27+
if primary
28+
attributes[primary], attributes[0] = attributes[0], attributes[primary]
2429
end
2530

2631
attributes

test/unit/attribute_test.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def create_attribute(model, name)
4444
assert_equal %w{id a}, Domain::Attribute.from_model(Domain.new, Foo).map(&:name)
4545
end
4646

47-
test "from_model should return attributes with PK first if sort is false and prepend_primary is true" do
48-
RailsERD.options[:sort] = false
47+
test "from_model should return attributes with PK first if prepend_primary is true" do
48+
RailsERD.options[:sort] = true
4949
RailsERD.options[:prepend_primary] = true
5050

5151
create_model "Foo"

0 commit comments

Comments
 (0)