diff options
| author | Teddy Wing | 2017-09-22 14:10:45 +0200 |
|---|---|---|
| committer | Teddy Wing | 2017-09-22 14:10:45 +0200 |
| commit | 2d7ce83439f29d261f0c5ec05140359218cfe661 (patch) | |
| tree | 8b958dc8a247721b6ac3f914419bad0257cfec21 | |
| parent | 9086e4c7d253927e7fad07bcd4eb194eeff393ca (diff) | |
| download | chouette-core-2d7ce83439f29d261f0c5ec05140359218cfe661.tar.bz2 | |
ModelAttribute: Add `#from_code` method
Enables finding a `ModelAttribute` by a string code combining klass and
name.
Refs #4401
| -rw-r--r-- | lib/model_attribute.rb | 8 | ||||
| -rw-r--r-- | spec/lib/model_attribute_spec.rb | 12 |
2 files changed, 20 insertions, 0 deletions
diff --git a/lib/model_attribute.rb b/lib/model_attribute.rb index 78c9168eb..60580e306 100644 --- a/lib/model_attribute.rb +++ b/lib/model_attribute.rb @@ -21,6 +21,14 @@ class ModelAttribute all.group_by(&:klass) end + def self.from_code(code) + klass, name = code.split('#').map(&:to_sym) + + methods_by_class(klass).select do |model_attr| + model_attr.name == name + end.first + end + def self.methods_by_class(klass) all.select do |model_attr| model_attr.klass == klass diff --git a/spec/lib/model_attribute_spec.rb b/spec/lib/model_attribute_spec.rb index 0ca90430f..427e01490 100644 --- a/spec/lib/model_attribute_spec.rb +++ b/spec/lib/model_attribute_spec.rb @@ -30,6 +30,18 @@ RSpec.describe ModelAttribute do end end + describe ".from_code" do + it "returns a ModelAttribute from a given code" do + ModelAttribute.instance_variable_set(:@__all__, [ + ModelAttribute.new(:journey_pattern, :name, :string) + ]) + + expect(ModelAttribute.from_code('journey_pattern#name')).to eq( + ModelAttribute.new(:journey_pattern, :name, :string) + ) + end + end + describe ".group_by_class" do it "returns all ModelAttributes grouped by klass" do ModelAttribute.instance_variable_set(:@__all__, [ |
