Class: JennCad::Commands::NewPart

Inherits:
Dry::CLI::Command
  • Object
show all
Includes:
ActiveSupport::Inflector
Defined in:
lib/jenncad/commands.rb

Instance Method Summary collapse

Instance Method Details

#call(name:) ⇒ Object



109
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
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
# File 'lib/jenncad/commands.rb', line 109

def call(name:, **)
  dir = Dir.pwd.split("/").last
  executable = underscore(dir)+".rb"
  executable_class = camelize(dir)
  unless File.exists?(executable)
    puts "Could not find #{executable}. Are you in a JennCad project directory?"
    exit
  end
  FileUtils.mkdir_p("parts")
  name = underscore(name)
  classname = camelize(name)
  filename = "parts/#{name}.rb"
  if File.exists?(filename)
    puts "File #{filename} already exists."
    exit
  end
  File.open(filename, "w") do |f|
    f.puts "class #{classname} < Part"
    f.puts "  def initialize(opts={})"
    f.puts "    @x = 10"
    f.puts "    @y = 10"
    f.puts "    @z = 5"
    f.puts "  end"
    f.puts ""
    f.puts "  def part"
    f.puts "    base = cube(x: @x, y: @y, z: @z)"
    f.puts "    res = base.fix"
    f.puts "    res"
    f.puts "  end"
    f.puts "end"
  end

  lines  = File.readlines(executable)
  magic_line = nil;
  lines.each_with_index do |l, i|
    if l.rindex(MAGIC)
      magic_line = i
    end
  end
  puts "part #{filename} created."
  if !magic_line
    puts "In your #{executable} add to class #{executable_class}:"
    puts "  def #{name}"
    puts "    #{classname}.new(config)"
    puts "  end"
    puts ""
    puts "For jenncad to insert this line automatically, add this line to your project file before the \"end\"-statement of your class:"
    puts "##{MAGIC}"
  else
    data  = "\n"
    data += "  def #{name}\n"
    data += "    #{classname}.new(config)\n"
    data += "  end\n"
    lines.insert(magic_line, data)
    f = File.open(executable, "w")
    f.write(lines.join)
    f.close
  end


end