models.rb 2.03 KB
require 'active_record'

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => "db.sqlite")

class Expression < ActiveRecord::Base
  belongs_to :filter
  
  validates_presence_of :field_name
  validates_presence_of :operator
  validates_presence_of :expr_value
  
  validates_format_of :operator, :with => /^(contains|starts with)$/
  
  def self.migration
    Class.new(ActiveRecord::Migration).tap { |c|
      c.class_eval do 
        def self.up
          create_table :expressions do |t|
            t.string :field_name
            t.string :operator
            t.string :expr_value
            t.belongs_to(:filter)
            t.boolean :case_sensitive
            t.timestamps
          end
        end
        
        def self.down
          drop_table :expressions
        end
      end
    }
  end
end

class Filter < ActiveRecord::Base
  has_many :expressions, :dependent => :destroy
  
  validates_presence_of :name
  validates_presence_of :destination_folder
  
  def expressions=(hash_or_list)
    old_ids, new_ids = expressions.map(&:id), []
    if hash_or_list.kind_of?(Hash)
      hash_or_list.each_pair do |k, v|
        if k =~ /^\d+$/
          expr = expressions.find(k)
          new_ids << expr.id
        else
          expr = expressions.build
          self.expressions << expr
        end
        expr.update_attributes(v)
      end
      (old_ids - new_ids).each do |id|
        expressions.find(id).destroy
      end
    else
      super(hash_or_list)
    end
  end
  
  after_save :save_expressions
  
  def save_expressions
    expressions.each { |expr|
      expr.filter_id = self.id
      expr.save!
    }
  end
  
  def self.migration
    Class.new(ActiveRecord::Migration).tap { |c|
      c.class_eval do 
        def self.up
          create_table :filters do |t|
            t.string :name
            t.string :destination_folder
            t.integer :order_num
            t.timestamps
          end
        end
        
        def self.down
          drop_table :filters
        end
      end
    }
  end
end