22
33module Alchemy
44 class ElementDefinition
5+ include ActiveModel ::Model
6+ include ActiveModel ::Attributes
7+ include Alchemy ::Hints
8+
9+ extend ActiveModel ::Translation
10+
11+ attribute :name , :string
12+ attribute :unique , :boolean , default : false
13+ attribute :amount , :integer , default : Float ::INFINITY
14+ attribute :taggable , :boolean , default : false
15+ attribute :compact , :boolean , default : false
16+ attribute :fixed , :boolean , default : false
17+ attribute :ingredients , default : [ ]
18+ attribute :nestable_elements , default : [ ]
19+ attribute :autogenerate , default : [ ]
20+ attribute :deprecated
21+ attribute :message
22+ attribute :warning
23+ attribute :hint
24+
25+ delegate :blank? , to : :name
26+
527 class << self
628 # Returns the definitions from elements.yml file.
729 #
830 # Place a +elements.yml+ file inside your apps +config/alchemy+ folder to define
931 # your own set of elements
1032 #
1133 def all
12- @definitions ||= read_definitions_file . map ( & :with_indifferent_access )
34+ @definitions ||= read_definitions_file . map { new ( ** _1 ) }
1335 end
1436
1537 # Add additional page definitions to collection.
@@ -23,23 +45,17 @@ def all
2345 # @param [Array || Hash]
2446 # You can pass a single element definition as Hash, or a collection of elements as Array.
2547 #
26- def add ( element )
48+ def add ( definition )
2749 all
28- if element . is_a? ( Array )
29- @definitions += element
30- elsif element . is_a? ( Hash )
31- @definitions << element
32- else
33- raise TypeError
34- end
50+ @definitions += Array . wrap ( definition ) . map { new ( **_1 ) }
3551 end
3652
3753 # Returns one element definition by given name.
3854 #
3955 def get ( name )
40- return { } if name . blank?
56+ return new if name . blank?
4157
42- all . detect { | a | a [ " name" ] == name }
58+ all . detect { _1 . name . casecmp ( name ) . zero? }
4359 end
4460
4561 def reset!
@@ -54,12 +70,20 @@ def definitions_file_path
5470
5571 private
5672
73+ def definitions_file
74+ File . read ( definitions_file_path )
75+ end
76+
77+ def definitions_file_exist?
78+ File . exist? ( definitions_file_path )
79+ end
80+
5781 # Reads the element definitions from +config/alchemy/elements.yml+.
5882 #
5983 def read_definitions_file
60- if File . exist? ( definitions_file_path )
84+ if definitions_file_exist?
6185 YAML . safe_load (
62- ERB . new ( File . read ( definitions_file_path ) ) . result ,
86+ ERB . new ( definitions_file ) . result ,
6387 permitted_classes : YAML_PERMITTED_CLASSES ,
6488 aliases : true
6589 ) || [ ]
@@ -69,5 +93,20 @@ def read_definitions_file
6993 end
7094 end
7195 end
96+
97+ def attributes
98+ super . with_indifferent_access
99+ end
100+ alias_method :definition , :attributes
101+
102+ def ingredients
103+ super . map ( &:with_indifferent_access )
104+ end
105+
106+ private
107+
108+ def hint_translation_scope
109+ :element_hints
110+ end
72111 end
73112end
0 commit comments