Sha256: b8bf190ba741885e04800630e79a96850a9049e953c68f9885f41048599bc446

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

module Settingson::Base

  extend ActiveSupport::Concern

  included do
    attr_accessor :settingson
  end

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

  def method_missing(symbol, *args)
    super
  rescue NoMethodError

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

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

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

    else # getter

      @settingson += ".#{symbol.to_s}"
      if record = self.class.find_by(name: @settingson)
        YAML.load(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(name: @settingson)
          record.update(value: args.first.to_yaml)
        else
          create(name: @settingson, value: args.first.to_yaml, settingson: @settingson)
        end

      else # getter

        if record = find_by(name: symbol.to_s)
          YAML.load record.value
        else
          new(settingson: symbol.to_s)
        end

      end
    end


  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
settingson-1.2.3 app/models/concerns/settingson/base.rb