Sha256: 2add8767eacad25ba44e71e519f40a39ee1b2b084bd5e2451588d119ea26bf14

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

require "active_record"
require "activerecord/mlang/version"
require "active_record/mlang/text"

module ActiveRecord
  module Mlang
    def self.included(base)
      base.extend ClassMethods
      base.set_text_reflection
    end

    module ClassMethods
      def text_class_name(text_class_name=nil)
        if text_class_name
          self.text_class_name = text_class_name
        end
        @text_class_name || (self.name + "Text")
      end

      def text_class_name=(text_class_name)
        @text_class_name = text_class_name
        self.set_text_reflection
      end

      def text
        self.text_class_name.safe_constantize
      end

      def has_text?
        !!self.text
      end

      def text_attrs(*args)
        args.each do |arg|
          define_method(arg.to_sym){
            self.text.__send__(arg)
          }
        end
      end

      def has_many_fkey
        if self.text
          self.text.parent_fkey
        else
          :parent_id
        end
      end

      def set_text_reflection
        has_many :texts, class_name: self.text_class_name, foreign_key: self.has_many_fkey
      end
    end

    def text(locale=nil)
      locale ||= I18n.default_locale
      if self.persisted? && lang = Lang[locale]
        texts.find_or_create_by(lang_id: lang.id)
      else
        nil
      end
    end
  end
end

require 'active_record/mlang/lang'
require 'active_record/mlang/lang_text'
require 'active_record/mlang/railtie' if defined?(Rails::Railtie)

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activerecord-mlang-0.0.6 lib/active_record/mlang.rb