Module: Slugifiable::Model
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/slugifiable/model.rb
Constant Summary collapse
- DEFAULT_SLUG_GENERATION_STRATEGY =
This concern makes objects have a string slug based on their ID or another specified attribute
To use, include this in any ActiveRecord model: “‘ include Slugifiable::Model “`
By default all slugs will be a string computed from the record ID: “‘ generate_slug_based_on :id “`
but optionally, you can also specify to compute the slug as a number: “‘ generate_slug_based_on id: :number “`
or compute the slug based off any other attribute: “‘ generate_slug_based_on :name “`
:compute_slug_as_string
- DEFAULT_SLUG_STRING_LENGTH =
11
- DEFAULT_SLUG_NUMBER_LENGTH =
6
Instance Method Summary collapse
- #compute_slug ⇒ Object
- #compute_slug_as_number(length = DEFAULT_SLUG_NUMBER_LENGTH) ⇒ Object
- #compute_slug_as_string(length = DEFAULT_SLUG_STRING_LENGTH) ⇒ Object
- #compute_slug_based_on_attribute(attribute_name) ⇒ Object
- #method_missing(missing_method, *args, &block) ⇒ Object
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(missing_method, *args, &block) ⇒ Object
46 47 48 49 50 51 52 |
# File 'lib/slugifiable/model.rb', line 46 def method_missing(missing_method, *args, &block) if missing_method.to_s == "slug" && !self.methods.include?(:slug) compute_slug else super end end |
Instance Method Details
#compute_slug ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/slugifiable/model.rb', line 54 def compute_slug strategy, = determine_slug_generation_method length = [:length] if .is_a?(Hash) || nil if strategy == :compute_slug_based_on_attribute self.send(strategy, ) else self.send(strategy, length) end end |
#compute_slug_as_number(length = DEFAULT_SLUG_NUMBER_LENGTH) ⇒ Object
71 72 73 74 |
# File 'lib/slugifiable/model.rb', line 71 def compute_slug_as_number(length = DEFAULT_SLUG_NUMBER_LENGTH) length ||= DEFAULT_SLUG_NUMBER_LENGTH generate_random_number_based_on_id_hex(length) end |
#compute_slug_as_string(length = DEFAULT_SLUG_STRING_LENGTH) ⇒ Object
66 67 68 69 |
# File 'lib/slugifiable/model.rb', line 66 def compute_slug_as_string(length = DEFAULT_SLUG_STRING_LENGTH) length ||= DEFAULT_SLUG_STRING_LENGTH (Digest::SHA2.hexdigest self.id.to_s).first(length) end |
#compute_slug_based_on_attribute(attribute_name) ⇒ Object
76 77 78 79 80 81 82 83 84 |
# File 'lib/slugifiable/model.rb', line 76 def compute_slug_based_on_attribute(attribute_name) return compute_slug_as_string unless self.attributes.include?(attribute_name.to_s) base_slug = self.send(attribute_name)&.to_s&.strip&.parameterize base_slug = base_slug.presence || generate_random_number_based_on_id_hex unique_slug = generate_unique_slug(base_slug) unique_slug.presence || generate_random_number_based_on_id_hex end |