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.



9
10
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
# File 'lib/ember_serialize.rb', line 9

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/"
  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.



4
5
6
# File 'lib/ember_serialize.rb', line 4

def javascripts_dir
  @javascripts_dir
end

.models_dirObject

Returns the value of attribute models_dir.



4
5
6
# File 'lib/ember_serialize.rb', line 4

def models_dir
  @models_dir
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



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

def args
  @args
end

#eaiObject

Returns the value of attribute eai.



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

def eai
  @eai
end

#easObject

Returns the value of attribute eas.



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

def eas
  @eas
end

#eenObject

Returns the value of attribute een.



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

def een
  @een
end

#eigObject

Returns the value of attribute eig.



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

def eig
  @eig
end

#estObject

Returns the value of attribute est.



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

def est
  @est
end

#extensionObject

Returns the value of attribute extension.



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

def extension
  @extension
end

#javascripts_dirObject

Returns the value of attribute javascripts_dir.



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

def javascripts_dir
  @javascripts_dir
end

#missingObject

Returns the value of attribute missing.



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

def missing
  @missing
end

#models_dirObject

Returns the value of attribute models_dir.



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

def models_dir
  @models_dir
end

Instance Method Details

#camel(name) ⇒ Object



60
61
62
# File 'lib/ember_serialize.rb', line 60

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

#detect_extensionObject



56
57
58
# File 'lib/ember_serialize.rb', line 56

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

#ember_app_name(javascripts_dir = @javascripts_dir) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/ember_serialize.rb', line 64

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



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

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



180
181
182
183
184
185
186
187
188
189
190
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
# File 'lib/ember_serialize.rb', line 180

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
    unless ignore.include? camel_name
      new_lines << line
    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") ]
  unless ignore.blank?
    content << "#{indent}# #{@eig} #{ignore.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



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
# File 'lib/ember_serialize.rb', line 123

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 = lines.grep(/#{@eig}/) do |l|
      l.gsub(/.*#{@eig} (.*)\s*$/, '\1').split(/\s*,\s*/)
    end.flatten.uniq.map {|t| camel(t)}
    as_is = lines.grep(/#{@eai}/) do |l|
      l.gsub(/.*#{@eai} (.*)\s*$/, '\1').split(/\s*,\s*/)
    end.flatten.uniq.map {|t| camel(t)}
    if @force_async.nil?
      async = lines.grep(/#{@eas}/) do |l|
        l.gsub(/.*#{@eai} (.*)\s*$/, '\1') == 'true'
      end.flatten.last
      async = true if async.nil?
    else
      async = @force_async
    end

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

    # catalog existing lines
    existing = {}
    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



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/ember_serialize.rb', line 94

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
        "#{indent}#{camel_name}: DS.hasMany('#{camel_name}'#{_async})"
      end
    end
  else
    existing[camel_name] || "#{indent}#{camel_name}: DS.attr('#{type}')"
  end
  [camel_name, line]
end

#model_class(serializer) ⇒ Object



227
228
229
230
231
232
233
234
235
# File 'lib/ember_serialize.rb', line 227

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

#schema(serializer) ⇒ Object



237
238
239
240
241
242
243
# File 'lib/ember_serialize.rb', line 237

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

#serialize(match = nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ember_serialize.rb', line 37

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
    schema = schema serializer
    model = model_class 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