Sha256: 2ae729e40b9305ab8811a36689163c28e076f4daf620687c5bbdae08f95d3b8a

Contents?: true

Size: 1.95 KB

Versions: 2

Compression:

Stored size: 1.95 KB

Contents

module Settingson::Base

  extend ActiveSupport::Concern

  included do
    attr_accessor :settingson
    serialize     :value
  end

  def to_s
    self.new_record? ? '' : self.value.to_s
  end

  def to_i
    self.new_record? ? 0 : self.value.to_i
  end

  def method_missing(symbol, *args)
    super
  rescue NoMethodError

    case symbol.to_s
    when /(.+)=/  # setter

      @settingson = "#{@settingson}.#{$1}"

      if record = self.class.find_by(key: @settingson) and args.first.nil?
        record.destroy
      elsif record
        record.update(value: args.first)
      else
        self.class.create(key: @settingson, value: args.first)
      end
    when /(.+)\?$/  # returns boolean
      @settingson = "#{@settingson}.#{$1}"
      self.class.find_by(key: @settingson).present?
    when /(.+)\!$/  # returns self or nil
      @settingson = "#{@settingson}.#{$1}"
      self.class.find_by(key: @settingson)
    else # returns values or self

      if not defined?(@settingson) or @settingson.blank?
          @settingson = "#{symbol.to_s}"
      else
          @settingson += ".#{symbol.to_s}"
      end

      if record = self.class.find_by(key: @settingson)
        record.value
      else
        self
      end

    end
  end

  module ClassMethods

    def method_missing(symbol, *args)
      super
    rescue NoMethodError

      case symbol.to_s
      when /(.+)=/  # setter

        @settingson = $1

        if record = find_by(key: @settingson) and args.first.nil?
          record.destroy
        elsif record
          record.update(value: args.first)
        else
          create(key: @settingson, value: args.first, settingson: @settingson)
        end

      when /(.+)\?$/  #
        find_by(key: $1).present?
      when /(.+)\!$/  # returns self or nil
        find_by(key: $1)
      else # getter

        if record = find_by(key: symbol.to_s)
          record.value
        else
          new(settingson: symbol.to_s)
        end

      end
    end


  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
settingson-1.3.1 app/models/concerns/settingson/base.rb
settingson-1.3.0 app/models/concerns/settingson/base.rb