Sha256: fa49c365d96ac07859c5517cdf0dd552499efaf0390e7f831be4e436e79af301

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

require 'i18n'

#
# Use as follows
# class Thing < ActiveRecord::Base
#   include ActsAsReadOnlyI18nLocalised
#   validates :slug, format: {with: /^[a-z]+[\-?[a-z]*]*$/},
#                    uniqueness: true,
#                    presence: true
#   acts_as_read_only_i18n_localised :name
# end
#
# thing = Thing.create(stub: 'test')
# puts(thing.name)
#
module ActsAsReadOnlyI18nLocalised
  def self.included(base)
    base.extend(ClassMethods)
  end

  #
  # Standard Ruby idiom for auto-adding class methods
  #
  module ClassMethods

    def acts_as_read_only_i18n_localised(*attributes)
      unless methods.include?(:custom_slug)
        define_method :custom_slug do
          send(:slug) if respond_to?(:slug)
        end
      end

      attributes.each do |attribute|
        define_method attribute do
          I18n.t("#{self.class.name.gsub(/::/, '/')
                                    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
                                    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
                                    .tr('-', '_')}.#{send(:custom_slug)}.#{attribute}"
                 .downcase.to_sym)
        end
      end
    end

    def use_custom_slug custom_slug_method
      define_method :custom_slug do
        send(custom_slug_method) if respond_to?(custom_slug_method)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_read_only_i18n_localised-0.0.2 lib/acts_as_read_only_i18n_localised.rb