Guest User

Untitled

a guest
Feb 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. # This
  2. require 'activesupport'
  3.  
  4. Object.class_eval do
  5. def self.has_behavior(behavior, options={})
  6. options.reverse_merge!({:from => name.underscore})
  7.  
  8. require "#{options[:from]}/#{behavior}"
  9. mod = "#{options[:from].camelize}::#{behavior.to_s.camelize}".constantize
  10.  
  11. include mod::InstanceMethods if defined?(mod::InstanceMethods)
  12. extend mod::ClassMethods if defined?(mod::ClassMethods)
  13. mod.initialize(self) if mod.respond_to?(:initialize)
  14. end
  15. end
  16.  
  17. # Or in Rails
  18. ActiveRecord::Base.class_eval do
  19.  
  20. def self.has_behavior(behavior, options={})
  21. options.reverse_merge!({:from => name.underscore})
  22.  
  23. require "#{options[:from]}/#{behavior}"
  24. mod = "#{options[:from].camelize}::#{behavior.to_s.camelize}".constantize
  25.  
  26. include mod::InstanceMethods if defined?(mod::InstanceMethods)
  27. extend mod::ClassMethods if defined?(mod::ClassMethods)
  28. mod.initialize(self) if mod.respond_to?(:initialize)
  29. end
  30.  
  31. end
  32.  
  33. # With
  34. module SharedBehaviors::Authenticated
  35. module InstanceMethods
  36. # Instance methods
  37. end
  38.  
  39. module ClassMethods
  40. # Class methods
  41. end
  42.  
  43. def initialize(klass)
  44. klass.class_eval do
  45. # do stuff
  46. end
  47.  
  48. klass.send(:foo)
  49. end
  50. end
  51.  
  52. # Or with
  53. module User::Authenticated
  54. module InstanceMethods
  55. # Instance methods
  56. end
  57.  
  58. module ClassMethods
  59. # Class methods
  60. end
  61.  
  62. def initialize(klass)
  63. klass.class_eval do
  64. # do stuff
  65. end
  66.  
  67. klass.send(:foo)
  68. end
  69. end
  70.  
  71. # Will:
  72. # 1. require 'shared_behaviors/authenticated'
  73. # 2. Get the module SharedBehaviors::Authenticated
  74. # 3. include SharedBehaviors::Authenticated::InstanceMethods if SharedBehaviors::Authenticated has InstanceMethods
  75. # 4. extend SharedBehaviors::Authenticated::ClassMethods if SharedBehaviors::Authenticated has ClassMethods
  76. # 5. call SharedBehaviors::Authenticated.initialize(User)
  77.  
  78. class User < ActiveRecord::Base
  79. has_behavior :authenticated, :from => :shared_behaviors
  80. end
  81.  
  82. # Will:
  83. # 1. require 'user/authenticated'
  84. # 2. Get the module User::Authenticated
  85. # 3. include User::Authenticated::InstanceMethods if User::Authenticated has InstanceMethods
  86. # 4. extend User::Authenticated::ClassMethods if User::Authenticated has ClassMethods
  87. # 5. call User::Authenticated.initialize(User)
  88.  
  89. class User < ActiveRecord::Base
  90. has_behavior :authenticated
  91. end
Add Comment
Please, Sign In to add comment