locomotivecms_mounter_pull_19 1.5.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (84) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +12 -0
  3. data/.rspec +3 -0
  4. data/.travis.yml +4 -0
  5. data/Gemfile +7 -0
  6. data/Gemfile.lock +131 -0
  7. data/MIT-LICENSE +20 -0
  8. data/NOTES +4 -0
  9. data/README.md +26 -0
  10. data/Rakefile +37 -0
  11. data/TODO +82 -0
  12. data/init.rb +2 -0
  13. data/lib/locomotive/mounter.rb +106 -0
  14. data/lib/locomotive/mounter/config.rb +21 -0
  15. data/lib/locomotive/mounter/engine_api.rb +205 -0
  16. data/lib/locomotive/mounter/exceptions.rb +44 -0
  17. data/lib/locomotive/mounter/extensions/compass.rb +38 -0
  18. data/lib/locomotive/mounter/extensions/httmultiparty.rb +22 -0
  19. data/lib/locomotive/mounter/extensions/sprockets.rb +46 -0
  20. data/lib/locomotive/mounter/extensions/tilt/css.rb +31 -0
  21. data/lib/locomotive/mounter/fields.rb +254 -0
  22. data/lib/locomotive/mounter/models/base.rb +42 -0
  23. data/lib/locomotive/mounter/models/content_asset.rb +84 -0
  24. data/lib/locomotive/mounter/models/content_entry.rb +372 -0
  25. data/lib/locomotive/mounter/models/content_field.rb +190 -0
  26. data/lib/locomotive/mounter/models/content_select_option.rb +29 -0
  27. data/lib/locomotive/mounter/models/content_type.rb +274 -0
  28. data/lib/locomotive/mounter/models/editable_element.rb +27 -0
  29. data/lib/locomotive/mounter/models/page.rb +442 -0
  30. data/lib/locomotive/mounter/models/site.rb +28 -0
  31. data/lib/locomotive/mounter/models/snippet.rb +55 -0
  32. data/lib/locomotive/mounter/models/theme_asset.rb +148 -0
  33. data/lib/locomotive/mounter/models/translation.rb +28 -0
  34. data/lib/locomotive/mounter/mounting_point.rb +65 -0
  35. data/lib/locomotive/mounter/reader/api.rb +64 -0
  36. data/lib/locomotive/mounter/reader/api/base.rb +67 -0
  37. data/lib/locomotive/mounter/reader/api/content_assets_reader.rb +39 -0
  38. data/lib/locomotive/mounter/reader/api/content_entries_reader.rb +142 -0
  39. data/lib/locomotive/mounter/reader/api/content_types_reader.rb +76 -0
  40. data/lib/locomotive/mounter/reader/api/pages_reader.rb +192 -0
  41. data/lib/locomotive/mounter/reader/api/site_reader.rb +42 -0
  42. data/lib/locomotive/mounter/reader/api/snippets_reader.rb +61 -0
  43. data/lib/locomotive/mounter/reader/api/theme_assets_reader.rb +42 -0
  44. data/lib/locomotive/mounter/reader/api/translations_reader.rb +30 -0
  45. data/lib/locomotive/mounter/reader/file_system.rb +43 -0
  46. data/lib/locomotive/mounter/reader/file_system/base.rb +65 -0
  47. data/lib/locomotive/mounter/reader/file_system/content_assets_reader.rb +90 -0
  48. data/lib/locomotive/mounter/reader/file_system/content_entries_reader.rb +97 -0
  49. data/lib/locomotive/mounter/reader/file_system/content_types_reader.rb +88 -0
  50. data/lib/locomotive/mounter/reader/file_system/pages_reader.rb +211 -0
  51. data/lib/locomotive/mounter/reader/file_system/site_reader.rb +27 -0
  52. data/lib/locomotive/mounter/reader/file_system/snippets_reader.rb +115 -0
  53. data/lib/locomotive/mounter/reader/file_system/theme_assets_reader.rb +83 -0
  54. data/lib/locomotive/mounter/reader/file_system/translations_reader.rb +36 -0
  55. data/lib/locomotive/mounter/reader/runner.rb +89 -0
  56. data/lib/locomotive/mounter/utils/hash.rb +31 -0
  57. data/lib/locomotive/mounter/utils/output.rb +124 -0
  58. data/lib/locomotive/mounter/utils/string.rb +40 -0
  59. data/lib/locomotive/mounter/utils/yaml.rb +125 -0
  60. data/lib/locomotive/mounter/utils/yaml_front_matters_template.rb +45 -0
  61. data/lib/locomotive/mounter/version.rb +8 -0
  62. data/lib/locomotive/mounter/writer/api.rb +74 -0
  63. data/lib/locomotive/mounter/writer/api/base.rb +172 -0
  64. data/lib/locomotive/mounter/writer/api/content_assets_writer.rb +74 -0
  65. data/lib/locomotive/mounter/writer/api/content_entries_writer.rb +227 -0
  66. data/lib/locomotive/mounter/writer/api/content_types_writer.rb +151 -0
  67. data/lib/locomotive/mounter/writer/api/pages_writer.rb +250 -0
  68. data/lib/locomotive/mounter/writer/api/site_writer.rb +125 -0
  69. data/lib/locomotive/mounter/writer/api/snippets_writer.rb +111 -0
  70. data/lib/locomotive/mounter/writer/api/theme_assets_writer.rb +201 -0
  71. data/lib/locomotive/mounter/writer/api/translations_writer.rb +85 -0
  72. data/lib/locomotive/mounter/writer/file_system.rb +44 -0
  73. data/lib/locomotive/mounter/writer/file_system/base.rb +70 -0
  74. data/lib/locomotive/mounter/writer/file_system/content_assets_writer.rb +38 -0
  75. data/lib/locomotive/mounter/writer/file_system/content_entries_writer.rb +33 -0
  76. data/lib/locomotive/mounter/writer/file_system/content_types_writer.rb +32 -0
  77. data/lib/locomotive/mounter/writer/file_system/pages_writer.rb +93 -0
  78. data/lib/locomotive/mounter/writer/file_system/site_writer.rb +30 -0
  79. data/lib/locomotive/mounter/writer/file_system/snippets_writer.rb +59 -0
  80. data/lib/locomotive/mounter/writer/file_system/theme_assets_writer.rb +72 -0
  81. data/lib/locomotive/mounter/writer/file_system/translations_writer.rb +29 -0
  82. data/lib/locomotive/mounter/writer/runner.rb +73 -0
  83. data/locomotivecms_mounter.gemspec +64 -0
  84. metadata +539 -0
@@ -0,0 +1,21 @@
1
+ module Locomotive
2
+ module Mounter
3
+
4
+ class Config < Hash
5
+
6
+ def self.instance
7
+ @@instance ||= self.new
8
+ end
9
+
10
+ def self.register(attributes)
11
+ self.instance.merge!(attributes)
12
+ end
13
+
14
+ def self.[](key)
15
+ self.instance[key]
16
+ end
17
+
18
+ end
19
+
20
+ end
21
+ end
@@ -0,0 +1,205 @@
1
+ require 'uri'
2
+
3
+ module Locomotive
4
+ module Mounter
5
+
6
+ class EngineApi
7
+
8
+ include HTTMultiParty
9
+
10
+ format :json
11
+
12
+ # Get a new token from the Engine API and set it for
13
+ # this class. It raises an exception if the operation fails.
14
+ # Example of the base uri: locomotivecms.com, nocoffee.fr.
15
+ #
16
+ # @param [ Hash / Array ] *args A hash or parameters in that order: uri, email, password or uri, api_key
17
+ #
18
+ # @return [ String ] The new token
19
+ #
20
+ def self.set_token(*args)
21
+ _credentials = self.credentials(args)
22
+
23
+ uri = URI _credentials.delete(:uri)
24
+ self.base_uri uri.to_s
25
+ self.basic_auth uri.user, uri.password if uri.userinfo
26
+
27
+ response = post('/tokens.json', body: _credentials) #{ email: email, password: password })
28
+
29
+ if response.code < 400
30
+ self.default_params auth_token: response['token']
31
+ response['token']
32
+ elsif response.code == 404 # ssl option missing
33
+ raise WrongCredentials.new("#{uri}/tokens.json does not respond. Perhaps, the ssl option is missing in your config/deploy.yml file")
34
+ else
35
+ raise WrongCredentials.new("#{response['message']} (#{response.code})")
36
+ end
37
+ end
38
+
39
+ # Read a resource or a list of resources from the API
40
+ # Raise an exception if something went wrong.
41
+ #
42
+ # @param [ String ] resource_name The path to the resource (usually, the resource name)
43
+ # @param [ Hash ] query If we want to filter the results
44
+ # @param [ String ] locale The locale for the request
45
+ # @param [ Array ] attribute_names The attributes we want to keep in the response
46
+ #
47
+ def self.fetch(resource_name, query = {}, locale = nil, attribute_names = nil)
48
+ params = { query: query || {} }
49
+ params[:query][:locale] = locale if locale
50
+
51
+ url = "/#{resource_name}.json"
52
+ response = self.get(url, params)
53
+ data = response.parsed_response
54
+
55
+ if response.success?
56
+ object_or_list = self.keep_attributes(data, attribute_names)
57
+
58
+ if response.headers['x-total-pages']
59
+ PaginatedCollection.new(url, params, attribute_names).tap do |collection|
60
+ collection.list = object_or_list
61
+ collection.total_pages = response.headers['x-total-pages'].to_i
62
+ collection.total_entries = response.headers['x-total-entries'].to_i
63
+ end
64
+ else
65
+ object_or_list
66
+ end
67
+ else
68
+ raise ApiReadException.new(data['error'])
69
+ end
70
+ end
71
+
72
+ # Create a resource from the API.
73
+ # Raise an exception if something went wrong.
74
+ #
75
+ # @param [ String ] resource_name The path to the resource (usually, the resource name)
76
+ # @param [ Hash ] attributes The attributes of the resource
77
+ # @param [ String ] locale The locale for the request
78
+ # @param [ Array ] attribute_names The attributes we want to keep in the response
79
+ #
80
+ # @return [ Object] The response of the API
81
+ #
82
+ def self.create(resource_name, attributes, locale = nil, attribute_names = nil)
83
+ params = self.build_create_or_params(resource_name, attributes, locale)
84
+ response = self.post("/#{resource_name}.json", params)
85
+ data = response.parsed_response
86
+
87
+ if response.success?
88
+ self.keep_attributes(data, attribute_names)
89
+ else
90
+ raise ApiWriteException.new(data)
91
+ end
92
+ end
93
+
94
+ # Update a resource from the API.
95
+ # Raise an exception if something went wrong.
96
+ #
97
+ # @param [ String ] resource_name The path to the resource (usually, the resource name)
98
+ # @param [ String ] id The unique identifier of the resource
99
+ # @param [ Hash ] attributes The attributes of the resource
100
+ # @param [ String ] locale The locale for the request
101
+ # @param [ Array ] attribute_names The attributes we want to keep in the response
102
+ #
103
+ # @return [ Object] The response of the API
104
+ #
105
+ def self.update(resource_name, id, attributes, locale = nil, attribute_names = nil)
106
+ params = self.build_create_or_params(resource_name, attributes, locale)
107
+ response = self.put("/#{resource_name}/#{id}.json", params)
108
+ data = response.parsed_response
109
+
110
+ if response.success?
111
+ self.keep_attributes(data, attribute_names)
112
+ else
113
+ raise ApiWriteException.new(data)
114
+ end
115
+ end
116
+
117
+ def self.teardown
118
+ Locomotive::Mounter::EngineApi.default_options[:base_uri] = nil
119
+ Locomotive::Mounter::EngineApi.default_options[:base_auth] = nil
120
+ Locomotive::Mounter::EngineApi.default_options[:default_params] = {}
121
+ end
122
+
123
+ protected
124
+
125
+ def self.credentials(args)
126
+ if args.first.is_a?(Hash)
127
+ args.first
128
+ elsif args.size == 3
129
+ # uri, email, password
130
+ { uri: args[0], email: args[1], password: args[2] }
131
+ elsif args.size == 2
132
+ # uri, api_key
133
+ { uri: args[0], api_key: args[1] }
134
+ else
135
+ {}
136
+ end
137
+ end
138
+
139
+ def self.build_create_or_params(resource_name, attributes, locale)
140
+ name = resource_name.to_s.split('/').last.singularize
141
+
142
+ params = { query: { name => attributes } }
143
+ params[:query][:locale] = locale if locale
144
+
145
+ params
146
+ end
147
+
148
+ def self.keep_attributes(data, attribute_names)
149
+ return data if attribute_names.blank?
150
+
151
+ case data
152
+ when Hash then data.to_hash.delete_if { |k, _| !attribute_names.include?(k) }
153
+ when Array
154
+ data.map do |row|
155
+ row.delete_if { |k, _| !attribute_names.include?(k) }
156
+ end
157
+ else
158
+ data
159
+ end
160
+ end
161
+
162
+ end
163
+
164
+ class PaginatedCollection < Struct.new(:url, :params, :attribute_names)
165
+
166
+ attr_accessor :list, :total_pages, :total_entries
167
+
168
+ alias :size :total_entries
169
+
170
+ def each(&block)
171
+ if self.total_pages == 1 && self.list
172
+ self.list.each(&block)
173
+ else
174
+ self.paginated_each(&block)
175
+ end
176
+ end
177
+
178
+ def paginated_each(&block)
179
+ loop do
180
+ self.params[:query][:page] = self.page
181
+
182
+ response = Locomotive::Mounter::EngineApi.get(self.url, self.params)
183
+ data = response.parsed_response
184
+
185
+ if response.success?
186
+ self.list = Locomotive::Mounter::EngineApi.send(:keep_attributes, data, self.attribute_names)
187
+ self.list.each(&block)
188
+ else
189
+ raise ApiReadException.new(data['error'])
190
+ end
191
+
192
+ break if self.page >= self.total_pages
193
+
194
+ @page += 1
195
+ end
196
+ end
197
+
198
+ def page
199
+ @page ||= 1
200
+ end
201
+
202
+ end
203
+
204
+ end
205
+ end
@@ -0,0 +1,44 @@
1
+ module Locomotive
2
+ module Mounter
3
+
4
+ class DefaultException < ::Exception
5
+
6
+ def initialize(message = nil)
7
+ Locomotive::Mounter.logger.error message
8
+ super
9
+ end
10
+
11
+ end
12
+
13
+ class ReaderException < DefaultException
14
+ end
15
+
16
+ class WriterException < DefaultException
17
+ end
18
+
19
+ class ImplementationIsMissingException < DefaultException
20
+ end
21
+
22
+ class FieldDoesNotExistException < DefaultException
23
+ end
24
+
25
+ class UnknownContentTypeException < DefaultException
26
+ end
27
+
28
+ class DuplicateContentEntryException < DefaultException
29
+ end
30
+
31
+ class UnknownTemplateException < DefaultException
32
+ end
33
+
34
+ class WrongCredentials < DefaultException
35
+ end
36
+
37
+ class ApiReadException < DefaultException
38
+ end
39
+
40
+ class ApiWriteException < DefaultException
41
+ end
42
+
43
+ end
44
+ end
@@ -0,0 +1,38 @@
1
+ module Locomotive
2
+ module Mounter
3
+ module Extensions
4
+
5
+ module Compass
6
+
7
+ # Configure Compass for the current site.
8
+ # [DEPRECATED] we use sprockets-sass now
9
+ #
10
+ # @param [ String ] site_path The root directory of the site
11
+ #
12
+ def self.configure(site_path)
13
+ ::Compass.configuration do |config|
14
+ config.project_path = File.join(site_path, 'public')
15
+ config.http_path = '/'
16
+ config.css_dir = '../tmp/stylesheets'
17
+ config.sass_dir = 'stylesheets'
18
+ config.fonts_dir = 'fonts'
19
+ config.images_dir = 'images'
20
+ config.javascripts_dir = 'javascripts'
21
+ config.project_type = :stand_alone
22
+ config.output_style = :nested
23
+ config.line_comments = false
24
+ end
25
+ end
26
+
27
+ # # Return the Compass options
28
+ # #
29
+ # # @return [ Hash ] The Compass options
30
+ # def self.options
31
+ # ::Compass.configuration.to_sass_engine_options
32
+ # end
33
+
34
+ end
35
+
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,22 @@
1
+ # Patch for https://github.com/jwagener/httmultiparty/issues/11
2
+
3
+ module HTTMultiParty
4
+ module ClassMethods
5
+
6
+ private
7
+
8
+ def perform_request(http_method, path, options, &block) #:nodoc:
9
+ options = default_options.dup.merge(options)
10
+
11
+ # FIXME: default_params are not handled for some unknown reasons, so move them to the body instead
12
+ if http_method == MultipartPost || http_method == MultipartPut
13
+ default_params = options.delete(:default_params)
14
+ options[:body].merge!(default_params) if options[:body] && default_params
15
+ end
16
+
17
+ process_cookies(options)
18
+ HTTParty::Request.new(http_method, path, options).perform(&block)
19
+ end
20
+
21
+ end
22
+ end
@@ -0,0 +1,46 @@
1
+ require 'yui/compressor'
2
+
3
+ module Locomotive
4
+ module Mounter
5
+ module Extensions
6
+
7
+ module Sprockets
8
+
9
+ @@env = @@path = nil
10
+
11
+ # Build a Sprocket environment for the current site.
12
+ # This method returns an unique environment for each call
13
+ # unless the site_path changed.
14
+ #
15
+ # @param [ String ] site_path The root directory of the site
16
+ # @param [ Boolean ] minify Minify the js and css assets (default: false)
17
+ #
18
+ def self.environment(site_path, minify = false)
19
+ return @@env if @@env && @@path == site_path
20
+
21
+ @@path = site_path
22
+ @@env = ::Sprockets::Environment.new.tap do |env|
23
+ if minify && is_java_installed?
24
+ # minify javascripts and stylesheets
25
+ env.js_compressor = YUI::JavaScriptCompressor.new
26
+ env.css_compressor = YUI::CssCompressor.new
27
+ else
28
+ message = "[Important] YUICompressor requires java to be installed. The JAVA_HOME variable should also be set.\n"
29
+ Locomotive::Mounter.logger.warn message.colorize(color: :red)
30
+ end
31
+
32
+ %w(fonts stylesheets javascripts).each do |name|
33
+ env.append_path File.join(site_path, 'public', name)
34
+ end
35
+ end
36
+ end
37
+
38
+ def self.is_java_installed?
39
+ `which java` != '' && (!ENV['JAVA_HOME'].blank? && File.exists?(ENV['JAVA_HOME']))
40
+ end
41
+
42
+ end
43
+
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,31 @@
1
+ module Tilt
2
+
3
+ # Sass with Compass features
4
+ class SassWithCompassTemplate < SassTemplate
5
+
6
+ private
7
+
8
+ def sass_options
9
+ super.merge(::Compass.configuration.to_sass_engine_options)
10
+ end
11
+
12
+ end
13
+
14
+ Tilt.register 'sass', SassWithCompassTemplate
15
+ Tilt.prefer SassWithCompassTemplate
16
+
17
+ # Scss with Compass features
18
+ class ScssWithCompassTemplate < ScssTemplate
19
+
20
+ private
21
+
22
+ def sass_options
23
+ super.merge(::Compass.configuration.to_sass_engine_options)
24
+ end
25
+
26
+ end
27
+
28
+ Tilt.register 'scss', ScssWithCompassTemplate
29
+ Tilt.prefer ScssWithCompassTemplate
30
+
31
+ end
@@ -0,0 +1,254 @@
1
+ module Locomotive
2
+ module Mounter
3
+
4
+ module Fields
5
+
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ include ActiveSupport::Callbacks
10
+
11
+ define_callbacks :initialize
12
+
13
+ class << self; attr_accessor :_fields end
14
+
15
+ attr_accessor :_locales
16
+ end
17
+
18
+ # Default constructor
19
+ #
20
+ # @param [ Hash ] attributes The new attributes
21
+ #
22
+ def initialize(attributes = {})
23
+ run_callbacks :initialize do
24
+ _attributes = attributes.symbolize_keys
25
+
26
+ # set default values
27
+ self.class._fields.each do |name, options|
28
+ next if !options.key?(:default) || _attributes.key?(name)
29
+
30
+ _attributes[name] = options[:default]
31
+ end
32
+
33
+ # set default translation
34
+ self.add_locale(Locomotive::Mounter.locale)
35
+
36
+ self.write_attributes(_attributes)
37
+ end
38
+ end
39
+
40
+ # Set or replace the attributes of the current instance by the ones
41
+ # passed as parameter.
42
+ # It raises an exception if one of the keys is not included in the list of fields.
43
+ #
44
+ # @param [ Hash ] attributes The new attributes
45
+ #
46
+ def write_attributes(attributes)
47
+ return if attributes.blank?
48
+
49
+ attributes.each do |name, value|
50
+ unless self.class._fields.key?(name.to_sym) || self.respond_to?(:"#{name}=")
51
+ next if name.to_s == 'id'
52
+ raise FieldDoesNotExistException.new "[#{self.class.inspect}] setting an unknown attribute '#{name}' with the value '#{value.inspect}'"
53
+ end
54
+
55
+ if self.localized_field?(name) && value.is_a?(Hash)
56
+ self.send(:"#{name}_translations=", value)
57
+ else
58
+ self.send(:"#{name}=", value)
59
+ end
60
+ end
61
+ end
62
+
63
+ alias :attributes= :write_attributes
64
+
65
+ # Return the fields with their values
66
+ #
67
+ # @return [ Hash ] The attributes
68
+ #
69
+ def attributes
70
+ {}.tap do |_attributes|
71
+ self.class._fields.each do |name, options|
72
+ _attributes[name] = self.send(name.to_sym)
73
+ end
74
+ end
75
+ end
76
+
77
+ def [](name)
78
+ self.attributes[name.to_sym]
79
+ end
80
+
81
+ # Return the fields with their values and their translations
82
+ #
83
+ # @return [ Hash ] The attributes
84
+ #
85
+ def attributes_with_translations
86
+ {}.tap do |_attributes|
87
+ self.class._fields.each do |name, options|
88
+ next if options[:association]
89
+
90
+ if options[:localized]
91
+ value = self.send(:"#{name}_translations")
92
+
93
+ value = value.values.first if value.size == 1
94
+
95
+ value = nil if value.respond_to?(:empty?) && value.empty?
96
+
97
+ _attributes[name] = value
98
+ else
99
+ _attributes[name] = self.send(name.to_sym)
100
+ end
101
+ end
102
+ end
103
+ end
104
+
105
+ # Check if the field specified by the argument is localized
106
+ #
107
+ # @param [ String ] name Name of the field
108
+ #
109
+ # @return [ Boolean ] True if the field is localized
110
+ #
111
+ def localized_field?(name)
112
+ method_name = :"#{name}_localized?"
113
+ self.respond_to?(method_name) && self.send(method_name)
114
+ end
115
+
116
+ # List all the translations done on that model
117
+ #
118
+ # @return [ List ] List of locales
119
+ #
120
+ def translated_in
121
+ self._locales.map(&:to_sym)
122
+ end
123
+
124
+ # Tell if the object has been translated in the locale
125
+ # passed in parameter.
126
+ #
127
+ # @param [ String/Symbol ] locale
128
+ #
129
+ # @return [ Boolean ] True if one of the fields has been translated.
130
+ #
131
+ def translated_in?(locale)
132
+ self.translated_in.include?(locale.to_sym)
133
+ end
134
+
135
+ # Return a Hash of all the non blank attributes of the object.
136
+ # It also performs a couple of modifications: stringify keys and
137
+ # convert Symbol to String.
138
+ #
139
+ # @param [ Boolean ] translation Flag (by default true) to get the translations too.
140
+ #
141
+ # @return [ Hash ] The non blank attributes
142
+ #
143
+ def to_hash(translations = true)
144
+ hash = translations ? self.attributes_with_translations : self.attributes
145
+
146
+ hash.delete_if { |k, v| (!v.is_a?(FalseClass) && v.blank?) }
147
+
148
+ hash.each { |k, v| hash[k] = v.to_s if v.is_a?(Symbol) }
149
+
150
+ hash.deep_stringify_keys
151
+ end
152
+
153
+ # Provide a better output of the default to_yaml method
154
+ #
155
+ # @return [ String ] The YAML version of the object
156
+ #
157
+ def to_yaml
158
+ # get the attributes with their translations and get rid of all the symbols
159
+ object = self.to_hash
160
+
161
+ object.each do |key, value|
162
+ if value.is_a?(Array)
163
+ object[key] = if value.first.is_a?(String)
164
+ StyledYAML.inline(value) # inline array
165
+ else
166
+ value.map(&:to_hash)
167
+ end
168
+ end
169
+ end
170
+
171
+ StyledYAML.dump object
172
+ end
173
+
174
+ protected
175
+
176
+ def getter(name, options = {})
177
+ value = self.instance_variable_get(:"@#{name}")
178
+ if options[:localized]
179
+ value = (value || {})[Locomotive::Mounter.locale]
180
+ end
181
+ value
182
+ end
183
+
184
+ def setter(name, value, options = {})
185
+ if options[:localized]
186
+ # keep track of the current locale
187
+ self.add_locale(Locomotive::Mounter.locale)
188
+
189
+ translations = self.instance_variable_get(:"@#{name}") || {}
190
+ translations[Locomotive::Mounter.locale] = value
191
+ value = translations
192
+ end
193
+
194
+ if options[:type] == :array
195
+ klass = options[:class_name].constantize
196
+ value = value.map { |object| object.is_a?(Hash) ? klass.new(object) : object }
197
+ end
198
+
199
+ self.instance_variable_set(:"@#{name}", value)
200
+ end
201
+
202
+ def add_locale(locale)
203
+ self._locales ||= []
204
+ self._locales << locale.to_sym unless self._locales.include?(locale.to_sym)
205
+ end
206
+
207
+ module ClassMethods
208
+
209
+ # Add a field to the current instance. It creates getter/setter methods related to that field.
210
+ # A field can have translations if the option named localized is set to true.
211
+ #
212
+ # @param [ String ] name The name of the field
213
+ # @param [ Hash ] options The options related to the field.
214
+ #
215
+ def field(name, options = {})
216
+ options = { localized: false }.merge(options)
217
+
218
+ @_fields ||= {} # initialize the list of fields if nil
219
+
220
+ self._fields[name.to_sym] = options
221
+
222
+ class_eval <<-EOV
223
+ def #{name}
224
+ self.getter '#{name}', self.class._fields[:#{name}]
225
+ end
226
+
227
+ def #{name}=(value)
228
+ self.setter '#{name}', value, self.class._fields[:#{name}] #, #{options[:localized]}
229
+ end
230
+
231
+ def #{name}_localized?
232
+ #{options[:localized]}
233
+ end
234
+ EOV
235
+
236
+ if options[:localized]
237
+ class_eval <<-EOV
238
+ def #{name}_translations
239
+ @#{name} || {}
240
+ end
241
+
242
+ def #{name}_translations=(translations)
243
+ translations.each { |locale, value| self.add_locale(locale) }
244
+ @#{name} = translations.symbolize_keys
245
+ end
246
+ EOV
247
+ end
248
+ end
249
+
250
+ end
251
+
252
+ end
253
+ end
254
+ end