Skip to content

Commit

Permalink
Refactor to use ActiveAttr for ActiveModel support
Browse files Browse the repository at this point in the history
  • Loading branch information
karmajunkie committed Feb 23, 2012
1 parent c4c93e6 commit 22c6633
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 31 deletions.
1 change: 1 addition & 0 deletions commando.gemspec
Expand Up @@ -21,4 +21,5 @@ Gem::Specification.new do |s|
# specify any dependencies here; for example:
# s.add_development_dependency "rspec"
# s.add_runtime_dependency "rest-client"
s.add_runtime_dependency "active_attr"
end
1 change: 1 addition & 0 deletions lib/commando.rb
@@ -1,3 +1,4 @@
require 'active_attr'
require "commando/version"
require 'commando/invalid_command_error'
require 'commando/command'
Expand Down
51 changes: 20 additions & 31 deletions lib/commando/command.rb
@@ -1,13 +1,13 @@
class Commando::Command
include ActiveModel::Naming
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Serialization
include ActiveModel::Serializers::JSON
include ActiveAttr::Model
extend ActiveModel::Callbacks

define_model_callbacks :create, :perform, :initialize

cattr_accessor :commit_mode
attr_accessor :attributes
attribute :id

after_initialize :set_uuid

class << self
attr_accessor :perform_block
Expand All @@ -17,26 +17,6 @@ def self.perform(&block)
@perform_block = block
end

def self.property(property_name)

define_method(property_name) do
@attributes[property_name]
end
define_method("#{property_name}=") do |val|
@attributes[property_name] = val
end
end

def read_attribute_for_validation(key)
@attributes[key]
end


def initialize(params={})
@attributes = HashWithIndifferentAccess.new params.dup
@attributes[:id] = UUIDTools::UUID.timestamp_create.to_s if @attributes[:id].nil?
end

alias_method :params, :attributes

def as_json
Expand All @@ -57,6 +37,12 @@ def commit
self.perform
end

def initialize(*)
run_callbacks :initialize do
super
end
end

def dump
attributes.to_json
end
Expand All @@ -76,11 +62,9 @@ def perform!

def perform
raise "You need to define the perform block for #{self.class.name}" unless self.class.perform_block
self.instance_exec(&self.class.perform_block)
end

def id
params[:id]
run_callbacks :perform do
self.instance_exec(&self.class.perform_block)
end
end

def method_missing(method, *args)
Expand All @@ -93,4 +77,9 @@ def method_missing(method, *args)
super
end
end

private
def set_uuid
self.id = UUIDTools::UUID.timestamp_create.to_s if self.id.nil?
end
end

0 comments on commit 22c6633

Please sign in to comment.