darth10 / chordy

A Ruby DSL for printing guitar chords
MIT License
129 stars 13 forks source link

Code Organization #5

Closed latortuga closed 11 years ago

latortuga commented 11 years ago

Someone got downvoted pretty hard on reddit for saying that your code organization needs work - that guy was right but he wasn't helpful so here's some practical tips on how you can improve your code:

module Chordy
  class Chord
    ...
  end
end

This helps keep your class names specific to your namespace so anyone using a similar name in their app won't have issues with conflicts. This also means you have to go through all of your chord classes and update them to be nested inside a module.

c_sharp: 1,2,3,4,5,6
require 'yaml'
chord_data = YAML.load(File.open('chords.yml'))

def chord_lookup(desired_chord)
  chord_data[desired_chord].split(',')
end
darth10 commented 11 years ago

@latortuga Thanks for the feedback :heart:

Could you explain a bit more on the evil eval? I mean I could use Object#send instead for eval in the play function, but what about the use of class_eval? Can you suggest a better way of adding methods dynamically?

I also intentionally kept the chords as constant-returning methods of Chord instead of part of data/config files. The reason is easy sub-classing and monkey-patching, which would be useful if you wanted to refine a chord's definition as per your needs. If there's a way I can do that with data files, I'll surely go for it. Any suggestions?

latortuga commented 11 years ago

@darth10 sure thing - I was only talking about the regular ol' eval, not the class_eval which definitely has uses. The biggest problem with your (previous) usage of eval is that it uses unchecked user input to dynamically dispatch methods which means user input can execute arbitrary code. I think you can probably see why this is a bad thing. As far as defining methods with class_eval, more power to you!

Couple more tidbits:

# Gemfile
gemspec
# chordy.gemspec
...
  s.add_development_dependency 'gem_name', '~> 2.3'
...

You will have to unignore the gemspec file. Take a look at some other open source projects for information about how to put one together.

darth10 commented 11 years ago

Simply awesome input @latortuga!

I actually had added the gemspec file initially, but later removed it as I noticed you don't really need it in the repository to build a gem. Will add one soon.

I'll post these as new issues later.