diff options
author | Louise Crow <louise.crow@gmail.com> | 2015-06-11 10:05:28 +0100 |
---|---|---|
committer | gorm <gormer@gmail.com> | 2015-06-29 21:32:54 +0200 |
commit | a9471ddd30c97db554a8e0dde10417a86fe02c25 (patch) | |
tree | 4ed955cd1ae0954bd221e26c7e80c9fd4af80789 /app/models/concerns/public_body_derived_fields.rb | |
parent | ab00e035c8c5978d2a8aea2a914747c22494aa9a (diff) |
Move updating of derived attributes to a concern.mimes
Add spec to demonstrate that admin-added bodies aren't getting derived attributes.
Add a spec to demonstrate the problem setting the first letter for translations.
Demonstrate failure to update derived attributes in translations.
Diffstat (limited to 'app/models/concerns/public_body_derived_fields.rb')
-rw-r--r-- | app/models/concerns/public_body_derived_fields.rb | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/app/models/concerns/public_body_derived_fields.rb b/app/models/concerns/public_body_derived_fields.rb new file mode 100644 index 000000000..f389e3cbf --- /dev/null +++ b/app/models/concerns/public_body_derived_fields.rb @@ -0,0 +1,47 @@ +module PublicBodyDerivedFields + + extend ActiveSupport::Concern + + included do + before_save :set_first_letter + + # When name or short name is changed, also change the url name + def short_name=(short_name) + super + update_url_name + end + + def name=(name) + super + update_url_name + end + + end + + # Return the short name if present, or else long name + def short_or_long_name + if self.short_name.nil? || self.short_name.empty? + self.name.nil? ? "" : self.name + else + self.short_name + end + end + + # Set the first letter, which is used for faster queries + def set_first_letter + unless name.blank? + # we use a regex to ensure it works with utf-8/multi-byte + first_letter = Unicode.upcase name.scan(/^./mu)[0] + if first_letter != self.first_letter + self.first_letter = first_letter + end + end + end + + def update_url_name + if changed.include?('name') || changed.include?('short_name') + self.url_name = MySociety::Format.simplify_url_part(self.short_or_long_name, 'body') + end + end + +end |