Skip to content

Commit

Permalink
add syntactic sugar to link module instances with dynamic methods
Browse files Browse the repository at this point in the history
allows for basic linking such as my_account.add_contact(my_contact)
  • Loading branch information
davidsulc committed Dec 16, 2010
1 parent 09edbf3 commit 9b10ca4
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/sugarcrm.rb
Expand Up @@ -7,6 +7,7 @@
require 'sugarcrm/base'
require 'sugarcrm/connection'
require 'sugarcrm/dynamic_finder_match'
require 'sugarcrm/dynamic_relater_match'
require 'sugarcrm/exceptions'
require 'sugarcrm/module'
require 'sugarcrm/request'
Expand Down
23 changes: 22 additions & 1 deletion lib/sugarcrm/base.rb
Expand Up @@ -346,7 +346,28 @@ def delete
params[:deleted]= {:name => "deleted", :value => "1"}
(SugarCRM.connection.set_entry(self.class._module.name, params).class == Hash)
end


# add syntactic sugar to link module instances with dynamic add_* instance methods
# e.g. my_account.add_contact(my_contact) or # my_contact.add_case(my_case)
def method_missing(method_id, *arguments, &block)
if match = DynamicRelaterMatch.match(method_id)
self.class.class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{method_id}(*args)
raise "Too many arguments for method '#{method_id}'. You can only link modules one at a time." if args.size > 1
module_to_link = args.first
SugarCRM.connection.set_relationship(
self.class._module.name,
self.id,
'#{match.module_instance.pluralize}',
[module_to_link.id]
)
end
EOS
send(method_id, *arguments)
else
super
end
end

# Wrapper around class attribute
def attribute_methods_generated?
Expand Down
19 changes: 19 additions & 0 deletions lib/sugarcrm/dynamic_relater_match.rb
@@ -0,0 +1,19 @@
module SugarCRM
class DynamicRelaterMatch
def self.match(method)
dr_match = self.new(method)
dr_match.module_instance ? dr_match : nil
end

def initialize(method)
case method.to_s
when /^add_([_a-zA-Z]\w*)$/
@module_instance = $1
else
@module_instance = nil
end
end

attr_reader :module_instance
end
end

0 comments on commit 9b10ca4

Please sign in to comment.