Class: EmberSerialize::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/ember_serialize.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Serializer

Returns a new instance of Serializer.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ember_serialize.rb', line 11

def initialize(args)
  @args = args
  # args
  @missing = args.extras.include?(':create') ? :create : :skip
  @force_async = args.extras.grep(/^async\:/) {|e| e =~ /true/}.first
  # variables
  @est = "ember_serialize:start"
  @een = "ember_serialize:end"
  @eig = "ember_serialize:ignore"
  @eai = "ember_serialize:as_is"
  @eas = "ember_serialize:async"
  @javascripts_dir = self.class.javascripts_dir || "app/assets/javascripts/"
  @models_dir = self.class.models_dir || @javascripts_dir+"models/"
  @types = Hash.new(:string).merge({
    # string: :string,
    # text: :string,
    date: :date,
    datetime: :date,
    timestamp: :date,
    time: :date,
    primary_key: :number,
    float: :number,
    integer: :number,
    boolean: :boolean,
    decimal: :number
  })
  unless File.exists? @models_dir
    require 'fileutils'
    FileUtils.mkdir_p @models_dir
  end
  # engine / extension
  engine = args.extras.grep(/^engine\:/) {|e| e.gsub(/^.*:/,'').to_sym}.first
  if engine == :coffee
    @extension = ".js.coffee"
  elsif engine == :em
    @extension = ".js.em"
  else
    @extension = detect_extension
  end
end

Class Attribute Details

.javascripts_dirObject

Returns the value of attribute javascripts_dir.



6
7
8
# File 'lib/ember_serialize.rb', line 6

def javascripts_dir
  @javascripts_dir
end

.models_dirObject

Returns the value of attribute models_dir.



6
7
8
# File 'lib/ember_serialize.rb', line 6

def models_dir
  @models_dir
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def args
  @args
end

#eaiObject

Returns the value of attribute eai.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def eai
  @eai
end

#easObject

Returns the value of attribute eas.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def eas
  @eas
end

#eenObject

Returns the value of attribute een.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def een
  @een
end

#eigObject

Returns the value of attribute eig.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def eig
  @eig
end

#estObject

Returns the value of attribute est.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def est
  @est
end

#extensionObject

Returns the value of attribute extension.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def extension
  @extension
end

#javascripts_dirObject

Returns the value of attribute javascripts_dir.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def javascripts_dir
  @javascripts_dir
end

#missingObject

Returns the value of attribute missing.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def missing
  @missing
end

#models_dirObject

Returns the value of attribute models_dir.



9
10
11
# File 'lib/ember_serialize.rb', line 9

def models_dir
  @models_dir
end

Instance Method Details

#camel(name) ⇒ Object



76
77
78
# File 'lib/ember_serialize.rb', line 76

def camel(name)
  name.to_s.underscore.camelize(:lower)
end

#detect_extensionObject



72
73
74
# File 'lib/ember_serialize.rb', line 72

def detect_extension
  Dir[@models_dir+"*js.em"].blank? ? ".js.coffee" : ".js.em"
end

#ember_app_name(javascripts_dir = @javascripts_dir) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/ember_serialize.rb', line 80

def ember_app_name(javascripts_dir = @javascripts_dir)
  @app_name ||= begin
    appname = Dir[javascripts_dir+"*"].select do |f|
      File.file?(f)
    end.map do |f|
      open(f) do |f|
        f.each_line.detect do |l|
          /Ember.Application.create/.match(l)
        end
      end
    end.compact.first.strip.gsub /.*window\.(\w+) =.*$/, '\1'
  end
end

#ember_model(app_name, model, indent, extension) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/ember_serialize.rb', line 94

def ember_model(app_name, model, indent, extension)
  klass = if extension == '.js.em'
    "class #{app_name}.#{model.name} extends DS.Model"
  else
    "#{app_name}.#{model.name} = DS.Model.extend"
  end
  lines = <<MODEL
# for more details see: http://emberjs.com/guides/models/defining-models/

#{klass}
#{indent}# ember_serialize:start
#{indent}# ember_serialize:end
MODEL
  lines.split /\n/
end

#ember_model_build(schema, model, args) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/ember_serialize.rb', line 191

def ember_model_build(schema, model, args)
  return nil unless args && args.length == 8
  lines, line_start, line_end, existing, ignore, as_is, async, indent = args
  new_lines = []

  # build attributes
  schema[:attributes].each do |name,type|
    camel_name, line = if name =~ /_id$/ &&
        type == :integer &&
        !as_is.include?(name) &&
        !as_is.include?(camel(name))
      ember_reflect(model, name, :belongs_to, async, existing, indent, type)
    else
      ember_reflect(model, name, :attribute, async, existing, indent, type)
    end
    next if camel_name == 'id'
    unless ignore.include? camel_name
      new_lines << line
      ignore << camel_name
    end
  end

  # build associations
  schema[:associations].each do |key, assoc|
    next if assoc.nil?
    rel, table = assoc.flatten
    camel_name, line = ember_reflect(model, table, rel, async, existing, indent)
    unless ignore.include? camel_name
      new_lines << line
    end
  end

  # build final content
  content = [ lines[0..line_start].join("\n") ]
  # write original ignore setting
  ignore_setting = setting_ignore(lines)
  unless ignore_setting.blank?
    content << "#{indent}# #{@eig} #{ignore_setting.join(", ")}"
  end
  unless as_is.blank?
    content << "#{indent}# #{@eai} #{as_is.join(", ")}"
  end
  if async == false
    content << "#{indent}# #{@eas} false"
  end
  content << new_lines.join(",\n")
  content << lines[line_end..-1].join("\n")

  content.join("\n")
end

#ember_model_parse(ember_model_file, model) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/ember_serialize.rb', line 140

def ember_model_parse(ember_model_file, model)
  if !File.exists? ember_model_file
    if @missing == :create
      # create default file
      lines = ember_model ember_app_name, model, "  ", @extension
    else
      return nil
    end
  else
    lines = File.readlines(ember_model_file).map(&:rstrip)
  end

  # find start/end markers
  line_start = lines.index {|l| l =~ /#{@est}/}
  line_end = lines.index {|l| l =~ /#{@een}/}

  if line_start && line_end
    # find settings for ignore, as_is, and async
    ignore = setting_ignore lines
    as_is = setting_as_is lines
    if @force_async.nil?
      async = setting_async lines
    else
      async = @force_async
    end

    # match the indent of the start line
    indent = lines[line_start][/\A */]

    # catalog existing lines
    existing = {}
    outside = []
    lines.each_with_index do |line, i|
      next if line =~ /^\s*#/ # reject comments
      next unless line =~ /:\s*DS\./ #include DS lines
      # reformat the line
      name, ds = line.strip.gsub(/,$/,'').split(/:\s*/,2)
      name = camel name
      # save lines inside range as existing
      if i > line_start && i < line_end
        existing[name] = "#{indent}#{name}: #{ds}"
      else # ignore ones outside the range
        ignore << name
      end
    end
    [lines, line_start, line_end, existing, ignore.uniq, as_is, async, indent]
  else
    nil
  end
end

#ember_reflect(model, name, rel, async, existing, indent, type = 'string') ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/ember_serialize.rb', line 110

def ember_reflect(model, name, rel, async, existing, indent, type = 'string')
  foreign_name = name.to_s.gsub(/_id$/, '').to_sym
  _async = async ? ", {async: true}" : ''
  assoc = model.reflect_on_all_associations.select do |a|
    a.name == foreign_name && a.macro == rel.to_sym
  end.first
  camel_name = camel(name)
  line = if assoc
    if rel == :belongs_to || rel == :has_one
      camel_name = camel(foreign_name)
      if existing[camel_name].to_s =~ /belongsTo/
        existing[camel_name]
      else
        assoc_name = assoc.table_name.singularize
        "#{indent}#{camel_name}: DS.belongsTo('#{assoc_name}'#{_async})"
      end
    else
      if existing[camel_name].to_s =~ /hasMany/
        existing[camel_name]
      else
        assoc_name = assoc.table_name.singularize
        "#{indent}#{camel_name}: DS.hasMany('#{assoc_name}'#{_async})"
      end
    end
  else
    existing[camel_name] || "#{indent}#{camel_name}: DS.attr('#{@types[type]}')"
  end
  [camel_name, line]
end

#model_class(serializer) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/ember_serialize.rb', line 242

def model_class(serializer)
  if serializer.respond_to? :model_class
    begin
      return serializer.model_class
    rescue NameError
      return nil
    end
  end
  @model_classes ||= Hash.new do |h,k|
    h[k] = k.name.gsub(/Serializer$/,'').constantize
  end
  @model_classes[serializer]
end

#schema(serializer) ⇒ Object



256
257
258
259
260
261
262
# File 'lib/ember_serialize.rb', line 256

def schema(serializer)
  if serializer.respond_to? :schema
    serializer.schema
  else 
    {}
  end
end

#serialize(match = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ember_serialize.rb', line 52

def serialize(match = nil)
  # populate Rails descendants
  Rails.application.eager_load!

  # loop through serializers
  ActiveModel::Serializer.descendants.sort_by(&:name).each do |serializer|
    if match
      next unless serializer.name =~ /^#{match}/
    end
    model = model_class serializer
    next unless model
    schema = schema serializer
    ember_model_file = @models_dir + model.table_name.singularize + @extension
    new_content = ember_model_build(schema, model, ember_model_parse(ember_model_file, model))
    if new_content
      File.write ember_model_file, new_content
    end
  end
end

#setting_as_is(lines) ⇒ Object



270
271
272
273
274
# File 'lib/ember_serialize.rb', line 270

def setting_as_is(lines)
  lines.grep(/#{@eai}/) do |l|
    l.gsub(/.*#{@eai} (.*)\s*$/, '\1').split(/[\s,]+/)
  end.flatten.uniq.map {|t| camel(t)}
end

#setting_async(lines) ⇒ Object



276
277
278
279
280
281
# File 'lib/ember_serialize.rb', line 276

def setting_async(lines)
  async = lines.grep(/#{@eas}/) do |l|
    l.gsub(/.*#{@eas} (.*)\s*$/, '\1') == 'true'
  end.flatten.last
  async.nil? ? true : async
end

#setting_ignore(lines) ⇒ Object



264
265
266
267
268
# File 'lib/ember_serialize.rb', line 264

def setting_ignore(lines)
  lines.grep(/#{@eig}/) do |l|
    l.gsub(/.*#{@eig} (.*)\s*$/, '\1').split(/[\s,]+/)
  end.flatten.uniq.map {|t| camel(t)}
end