Last active
July 3, 2018 06:55
-
-
Save zlei1/903361e4886601c95c658a7acfc8daa6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module EggConcern | |
| def append_features base | |
| super | |
| base.instance_eval(&@_class_methods) | |
| base.class_eval(&@_class_eval) | |
| end | |
| def included base = nil, &block | |
| super | |
| @_class_eval = block | |
| end | |
| def class_methods &block | |
| @_class_methods = block | |
| end | |
| end | |
| module ActsAsField | |
| extend EggConcern | |
| included do | |
| @@acts_as_fields = [] | |
| end | |
| class_methods do | |
| def field name, path | |
| result = class_variable_get(:@@acts_as_fields) | |
| result << name.to_sym | |
| class_variable_set(:@@acts_as_fields, result) | |
| define_method(name) do | |
| case path | |
| when String | |
| path.split(".").inject(self.latest_data) { |data, key| data[key] } | |
| when Proc | |
| path.call(self) | |
| end | |
| end | |
| end | |
| end | |
| def acts_as_fields | |
| self.class.class_variable_get :@@acts_as_fields | |
| end | |
| end | |
| class Device | |
| include ActsAsField | |
| field :device_type, "device_type" | |
| field :battery, "data.battery" | |
| field :node_info, "data.node_info" | |
| field :battery_to_text, proc { |device| | |
| "#{device.battery}%" | |
| } | |
| def latest_data | |
| { | |
| "data" => { | |
| "node_info" => "this is a sensor", | |
| "battery" => 90 | |
| }, | |
| "device_type" => "Sensor" | |
| } | |
| end | |
| end | |
| d = Device.new | |
| p d.node_info | |
| p d.battery_to_text | |
| p d.acts_as_fields | |
| # 扩展 | |
| # active_support | |
| require 'active_support/all' | |
| class A | |
| class_attribute :title | |
| cattr_accessor :title | |
| end | |
| A.title = "A" | |
| A.title | |
| module B | |
| mattr_accessor :title | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment