public
Description: ActiveRecord without persistance Plugin for Rails
Homepage:
Clone URL: git://github.com/remvee/active_form.git
active_form / lib / active_form.rb
100644 66 lines (55 sloc) 1.691 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# = ActiveForm - non persistent ActiveRecord
#
# Simple base class to make AR objects without a corresponding database
# table. These objects can still use AR validations but can't be saved
# to the database.
#
# == Example
#
# class FeedbackForm < ActiveForm
# column :email
# column :message, :type => :text
# validates_presence_of :email, :message
# end
#
class ActiveForm < ActiveRecord::Base
  def self.columns # :nodoc:
    @columns ||= []
  end
 
  # Define an attribute. It takes the following options:
  # [+:type+] schema type
  # [+:default+] default value
  # [+:null+] whether it is nullable
  # [+:human_name+] human readable name
  def self.column(name, options = {})
    name = name.to_s
    options.each { |k,v| options[k] = v.to_s if Symbol === v }
    
    if human_name = options.delete(:human_name)
      name.instance_variable_set('@human_name', human_name)
      def name.humanize; @human_name; end
    end
    
    columns << ActiveRecord::ConnectionAdapters::Column.new(
      name,
      options.delete(:default),
      options.delete(:type),
      options.include?(:null) ? options.delete(:null) : true
    )
    
    raise ArgumentError.new("unknown option(s) #{options.inspect}") unless options.empty?
  end
 
  def self.abstract_class # :nodoc:
    true
  end
  
  def save # :nodoc:
    if result = valid?
      callback(:before_save)
      callback(:before_create)
      
      # do nothing!
      
      callback(:after_save)
      callback(:after_create)
    end
    
    result
  end
  
  def save! # :nodoc:
    save or raise ActiveRecord::RecordInvalid.new(self)
  end
end