Class: Sparrow::Base
- Inherits:
-
Object
- Object
- Sparrow::Base
- Extended by:
- ActiveModel::Callbacks, ActiveModel::Translation, ClassMethods
- Includes:
- ActiveModel::Dirty, ActivemodelObjectInfo::Base
- Defined in:
- lib/sparrow/base.rb
Overview
对麻雀实体类进行基础类定义和设置通用的属性方法等。所有实际使用的实体类都要基于此类进行设置。
Constant Summary
Constants included from ClassMethods
ClassMethods::DEFAULT_PRIMARY_KEY_NAME
Instance Attribute Summary
Attributes included from ClassMethods
Instance Method Summary collapse
-
#attribute_names ⇒ Array<Symbol>
获取当前实例中通过类方法 ClassMethods#define_object_attribute 设定的属性。.
-
#attributes ⇒ Hash
获取当前实例中通过类设定属性的键值对,键名为属性名,值为对应属性的值。.
-
#i18n(name, type: :label, scope: nil, options: {}) ⇒ String
提供实例中快速获取 I18n 文本的方法。会根据当前类自动选择路径查找。详情参照对应同名类方法。.
-
#initialize(**attribute_settings) ⇒ Base
constructor
初始化基本实体类。.
Methods included from ClassMethods
attribute_keys, define_object_attribute, define_object_attributes
Constructor Details
#initialize(**attribute_settings) ⇒ Base
初始化基本实体类。
26 27 28 29 30 31 32 33 34 |
# File 'lib/sparrow/base.rb', line 26 def initialize(**attribute_settings) run_callbacks(:initialize) do attribute_settings.each do |key, value| # puts "key=#{key}, value=#{value}, respond=#{respond_to?(key.to_s + '=')}" __send__("#{key}=", value) if respond_to?("#{key}=") end true # 这里必须保证为true让block值为真,确保回调会被调用 end end |
Instance Method Details
#attribute_names ⇒ Array<Symbol>
获取当前实例中通过类方法 ClassMethods#define_object_attribute 设定的属性。
50 51 52 |
# File 'lib/sparrow/base.rb', line 50 def attribute_names self.class.attribute_keys.compact_blank.map(&:to_sym) end |
#attributes ⇒ Hash
获取当前实例中通过类设定属性的键值对,键名为属性名,值为对应属性的值。
41 42 43 |
# File 'lib/sparrow/base.rb', line 41 def attributes attribute_names.index_with { |attribute_name| __send__(attribute_name) } end |
#i18n(name, type: :label, scope: nil, options: {}) ⇒ String
提供实例中快速获取 I18n 文本的方法。会根据当前类自动选择路径查找。详情参照对应同名类方法。
65 66 67 |
# File 'lib/sparrow/base.rb', line 65 def i18n(name, type: :label, scope: nil, options: {}) self.class.i18n(name, type: type, scope: scope, options: ) end |