Skip to content

MR18 Mutant Gem

Dave Strus edited this page Feb 1, 2016 · 1 revision

Mutant Gem

Open lib/mutantcorp/mutant, and you'll find a couple of requires, and a module and submodule.

lib/mutantcorp/mutant.rb

require "mutantcorp/mutant/version"
require 'mutantcorp/mutant/mutant'

module Mutantcorp
  module Mutant
  end
end

If we expected to have many classes within the Mutant module, we'd want to define them in new files in the lib/mutantcorp/mutant directory. As it is, let's just define the Mutant class right here.

Just stick the Mutant class from the roster project inside the Mutantcorp::Mutant module.

module Mutantcorp
  module Mutant
    class Mutant
      ATTRIBUTE_NAMES = [:real_name, :mutant_name, :power]

      def self.attribute_names
        ATTRIBUTE_NAMES
      end

      attr_accessor *ATTRIBUTE_NAMES

      def description
        "#{mutant_name} (also known as #{real_name}) has an incredible power: #{power}."
      end

      def attributes
        attribute_collection = {}
        ATTRIBUTE_NAMES.each do |attribute_name|
          attribute_collection[attribute_name] = send(attribute_name)
        end
        attribute_collection
      end
    end
  end
end

Let's try it out. Thankfully, we don't have to go through the whole process of building, installing, and requiring. Bundler provided us with a console script that requires everything we need to take our code for a test drive.

Let's look at the console script.

#!/usr/bin/env ruby

require "bundler/setup"
require "mutantcorp/mutant"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "irb"
IRB.start

Notice that there's code commented out to use Pry instead of IRB. Let's go ahead and make that switch. There's a comment in there about adding Pry to the Gemfile. Ignore that for a moment, and just swap out IRB for Pry.

#!/usr/bin/env ruby

require "bundler/setup"
require "mutantcorp/mutant"

require "pry"
Pry.start

# require "irb"
# IRB.start

Try running the console script from the terminal.

$ bin/console
bin/console:5:in `require': cannot load such file -- pry (LoadError)
	from bin/console:5:in `<main>'

It failed to find Pry, even though we have the gem installed. Here's where Bundler's primary purpose—dependency management—comes into play.