Oracle Instant Client

| Comments

So today was my first day as a Software Engineer at Time Inc. I can already tell it’s going to be such an incredible learning experience, and all we did was environment setup today.

The hardest part about all of this, was setting up the client for an Oracle database. An Oracle database is an object-relational database management system, which means that it is similar to a relational-database but uses an object-oriented model. Essential, it supports objects, classes and inheritence directly in the database schemas and query language, as well as supports custom data-types and methods.

The process of installing took me roughly 4 hours, even with the help of some great blog guides. So I thought I would give it a go at simplyifying the process even further.

1. The first step is to find your operating system in order to download the necessary components. I was using a Mac OS X Intel. Those options can be found here .


2. Download Instant Client Basic, SDK and SQL*Plus. SDK stands for software development kit, and is a set of developer tools. SQLPlus is a command line tool for making SQL queries to an Oracle database. Those options can be found here. One thing I will make note of, I originally tried downloading the latest Version, 11.2.0.3.0, but ended up having to remove all those directories and start over again with Version 10.2.0.4 with the 64-bit package.


3. When I downloaded the instant client, SDK and SQLPlus, they were already unzipped, so I was able to bypass that step (I was using OS X, 10.8.5). The next step was to make a directory to store instant client: mkdir ~/opt/oracle


4. Because instant client, SQL*Plus and SDK all download into different directories, I combined the SQLPlus and SDK directories into the instant client directory, making everything much more compact.


5. Next, I moved my instantclient directory into my /opt/oracle directory: mv instantclient /opt/oracle


6. Setting up sym links to the libraries:

  ln -s libclntsh.dylib.10.1 libclntsh.dylib
  ln -s libocci.dylib.10.1 libocci.dylib

7. The next step is to set up ORACLE_HOME, NLS_LANG and DYLD_LIBRARY_PATH variables. I chose to set up my variables inside my .bash_profile:

  export ORACLE_HOME=/opt/oracle
  #export ORACLE_HOME=/usr/local/oracle
  export DYLD_LIBRARY_PATH=$ORACLE_HOME/instantclient
  export LD_LIBRARY_PATH=$DYLD_LIBRARY_PATH
  export SQLPATH=$ORACLE_HOME/instantclient
  export ARCHFLAGS="-arch x86_64"
  export NLS_LANG="AMERICAN_AMERICA.UTF8"
  export TNS_ADMIN=$ORACLE_HOME/network/admin
  export PATH=$PATH:$MAVEN_HOME/bin:$SVN_HOME/bin:$GIT_HOME/bin:$AMQ_PATH/bin:$DYLD_LIBRARY_PATH

Obviously, these paths will change base on your own selection for directory names.


8. The final step is to put SQL*Plus in your $PATH. I did this by creating a symlink (I already had usr/local/bin in my $PATH)

  ln -s /opt/oracle/instantclient/sqlplus /usr/local/bin/sqlplus

You can test to make sure this works by running which sqlplus, which should return /usr/local/bin/sqlplus

9. The final step is to test it all out! Try running gem install ruby-oci8 and Oracle instant client should be all set up!

    __Helpful Links:__
  • http://ruby-oci8.rubyforge.org/en/file.install-instant-client.html
  • http://www.pixellatedvisions.com/2009/03/25/rails-on-oracle-part-1-installing-the-oracle-instant-client-on-mac-os-x

Pluck

| Comments

Recently during a pairing session, I learned about the ActiveRecord query, pluck. Essentially, it performs a single column select and returns an array of that data.

Say you have a Person class, and you want to select all the names for everyone in that class, all you would need to call is:

  Person.pluck(:name)
  =>["Victoria", "Nat", "Peach"]

Essentially, this is like calling,

  SELECT name FROM person;

You can also use pluck to replace using collect and map.

  Person.select(:name).map { |p| p.name }
  =>["Victoria", "Nat", "Peach"]

Instead,

  Person.pluck(:name)
  =>["Victoria", "Nat", "Peach"]

Using pluck in this case is far more efficient than using map to return the same set of results. In the example with map, a full ActiveRecord Person record is returned and then the map is performed. pluck works directly at a database level, and only queries for exactly the information requested.

    Helpful Links:
  1. http://guides.rubyonrails.org/active_record_querying.html#pluck
  2. http://apidock.com/rails/ActiveRecord/Calculations/pluck
  3. http://blog.hashrocket.com/posts/rails-quick-tips-activerecord-calculations-pluck

Respond_to

| Comments

My last post was about method_missing. Since that post, I’ve gotten to play around with method_missing a lot, and think I’ve begun to grasp its power. It’s a crazy tool, and one that can be dangerous if not used wisely.

One thing I learned while rewriting the functionality of method_missing is that you must reopen and rewrite respond_to as well. respond_to is used to determine if an object responds to a method, i.e. allows the object to know a method is being called on it.

Becase method_missing allows you to call undefined methods, the object needs to know in some capicty what those are. In the below example, I have written method_missing to be able to use .get_* and .set_* in order to access object in my database. The method name gets passed as a symbol to method missing, so it must be turned into a string before being used.

def self.method_missing(method_name, *args, &block)
  method_string = method_name.to_s
  if method_string.start_with?("get_")
    #do xyz
  elsif method_string.start)with?("set_")
    #do xyz
  else
    super
  end
end

def self.respond_to?(method_sym, include_private = false)
  if method_sym.to_s =~ /^get_(.*)$/ || method_sym.to_s =~ /^set_(.*)$/
    true
  else
    super
  end
end

Here, respond_to now responds to my version of method_missing. I am essentially searching if the string version of my method includes get_* or set_* and if it does, it is a method that can be called on an object.

The include_private = false is necessary because by default, respond_to must be passed additional parameters to search for private methods. Methods are private for a reason, they don’t need to be accessed everywhere and by every object.

Also in both method_missing and respond_to my if/else clause ends by calling super. Essentially, if none of the above returns true, go back to your normal functionality and deliver me an error message.

Also note I am using class methods here. My practice with method_missing and respond_to was geared towards reading and writing objects to my database.

Method_missing

| Comments

Last night I learned about Ruby’s method_missing.

As Ruby code is executed, it travels up the chain of inheritence to discover where your methods are defined. It will execute the first line of code that matches the method name in the method lookup path.

And of course, when there is an instance where you attempt to call an undefined method, the NoMethodError exception is raised. When this happens, Ruby searches up levels of inheritence until it reaches class BasicObject, which is the parent class of all classes in Ruby. Once it reaches BasicObject and still is unable to find a method, NoMethodError is returned.

This is where method_missing comes in to play. method_missing is a type of metaprogramming that allows programmers to call methods without explicitely defining them.

class Test
  def method_missing(name, *args, &block)
    puts "NAME: #{name}"
    puts "ARG: #{args}"
    puts "BLOCK: #{block}"
  end

end

t = Test.new

t.some_method("arbitrary argument")

#=> NAME: some_method
    ARG: ["arbitrary argument"]
    BLOCK: 

In this example, the only method defined in my class is method_missing. I passed in the method name, optional arguments, and an optional block. Once I instantiate a new instance of the Test class, I call a method some_method on it. But some_method hasn’t been defined. Normally this would return NoMethodError but because I used method_missing, some_method is accessible to me.

As you can see in my definition of method_missing, I asked it to print out the method name, any potential arguments, and any potential blocks. some_method has method name and an argument, but not a block. Everything I attempted to call on my instance of the Test class is executed thanks to method_missing.

Coding Abroad

| Comments

I just got back from a week vacation in Paris. The highlight of my trip was the day I spent with two different Ruby developers. Through some twitter introductions, I was able to schedule a morning at Verseau Paris with founderTracy Loisel and an afternoon with Thibaut Assus, founder of Paris.rb.

It was so incredible to be welcome so whole-heartedly by developers abroad. Tracy was so willing to tell me his story, intrdouce me to his team, and show me around his office. And while there was a little bit of a language barrier (my french isn’t perfect), coding is international. We both have a story of why we started coding and Ruby provided a common language and basis of understanding. They even posted about me on facebook!

I had a very similiar experience in the afternoon with Thibaut. He welcomed me into his home, told me all about his projects, figured out we knew people in common, and we even laughed about how the PHP array method is bizarre. Commonality.

My experience with these developers really hammered home how welcoming the Ruby community is. I am a very new developer, and these amazing developers in Paris were each willing to spend a few hours with me. I don’t know if you can find that in other industries. It was incredibly reaffirming for me. I am so excited to spend the rest of my life coding. Programming isn’t people talking to computers, it’s people talking to people, and bringing people together. It’s amazing.

A Lesson in Linked Lists

| Comments

This morning, I learned what a linked list is. A linked list is a data structure that is comprised on a group of nodes. Essentially, each dataset is made up of it’s information, and a pointer. A pointer is a link to the next node in the data sequence. In the simplest of terms, if I am a dataset, I only know about myself, and the person that comes after me.

Linked lists are most commonly compared to arrays. They both store data, and both have their pros and cons. In compiled languages, arrays are a fixed size. If you define an array to have 100 elements, it has 100 elements. While there are methods to resize an array in compiled languages, from what I’ve read, it’s not an easy task. Linked lists allow for a significantly easier process for inserting and deleting data, without shifting entire groups of elements up or down.

So here is an example of a basic link list:

This small data sequence is going to be listed in alphabetical order. All linked lists start with HEAD, which denotes the begining of the data sequence. The head contains a pointer, which points to the first object in the data set. In this case, HEAD points to “Boston”. The first dataset, contains the name of the city, and a pointer to the following dataset, here it is San Fransico. San Francisco points to the end, which is always signified by NULL. The last dataset will always point to NULL.

So in this case, Boston only knows that it exists, and knows about San Fransico. San Francisco only knows they exist, and that NULL exists. They don’t know anything about Boston.

So the process for inserting another city is fairly simple. Say we wanted to insert New York. Because of the alphabetical order, you will want to insert it between Boston and San Francisco. To do so, all you need to do is make New York point to San Francisco, and change Boston to point to New York. There is no shifting of indexes, or anything like that.

However the process of searching a linked list is difficult. While in an array, if you were trying to find San Francisco you should simply do array[2] to access San Francisco, it’s a much more expensive process in linked lists. In this final example, in order to search for San Francisco, you have to start at head, move through Boston and New York, to finally arrive at the data you are searching for.

    Resources:
  1. http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
  2. http://www.youtube.com/watch?v=LOHBGyK3Hbs
  3. www.youtube.com/watch?v=oiW79L8VYXk

Ruby Marshaling

| Comments

As my semester at The Flatiron School winds down, we’ve been spending our time building our final projects. My group, Tyler Davis, Danny Olinsky, and Jesse La Russo, is building a modern-take on an old fashioned gold star board. Aka, you write a blog post? You get a gold star. You finish a Code School course? You get a gold star. We’ve built in a lot of other functionality (our own authentication and authorization, the ability for users to give each other stars, background cron jobs, etc. etc.), but that’s the gist of it.

The best thing about this whole process has been the things I’ve learned from the errors we get. In this way, I learned about the Ruby Marshal Module.

The Marshal Module essentially takes a collection of Ruby Objects and converts them into a byte stream, and then allows it to be stored and accessed elsewhere.

One of this big things with our project has been working with APIs in order to automate the processes of giving stars. The Treehouse API was particularly difficult to parse through, so for the time being, I created a dictionary to deal with their objects. Essentially, we want to give a star for every category a user completes.

  @@dictionary = {
  "Website Basics" => ["Website Basics"],
  "Technology Foundations" => ['Graphic Basics'],
  "Aesthetic Foundations" => ["Elements", "Principles", "Color Theory"],
  "HTML" => ["Introduction", "Text", "Lists", "Links", "Objects", "Tables", "Forms"],
  "CSS Foundations" => ["Introduction", "Selectors", "Data Types", "Text", "Box Model", "Page Layout", "Printing", "Framework Foundations"],
  "CSS3" => ["Selectors", "Typography", "Web Fonts", "Borders", "Gradients", "Backgrounds", "Transitions", "Transforms", "Animation", "Multi-Column Layouts", "Media Queries"],
  "Build a Responsive Website" => ["Introduction to Response Web Design", "Fluid Foundation", "Adaptive Design", "Responsive Design", "Advanced Techniques"],
  "Introduction to Programming" => ["Basics", "Control Structures", "Objects and Arrays", "Functions"],
  "JavaScript Foundations" => ["Introduction Variables", "JavaScript Strings", "JavaScript Numbers", "JavaScript Arrays", "JavaScript Functions", "JavaScript Objects"],
  "Ruby Foundations" => ["Ruby Basics", "Objects, Classes, and Variables", "Ruby Strings", "Ruby Numbers", "Ruby Arrays", "Ruby Hashes", "Ruby Methods", "Ruby Loops", "Ruby Blocks", "Ruby Procs & Lambdas", "Ruby Modules", "Ruby Core", "Standard Library", "Ruby Testing"],
  "Build a Simple Ruby on Rails Application" => ["Getting Started with Rails", "Rails Frontend Development", "Ruby on Rails Authentication", "Customizing Ruby on Rails Forms", "Writing Tests", "Rails Routing", "Testing the Whole App", "Building the Profile Page", "Rails Deployment"]
}

In this dictionary, the star (which is also the Treehouse badge category) is the key. The values (represented as an array of strings) are all the badges you can earn. Essentially, the values are the requirements a user must fulfill to receive a Treehouse Star. In order to do that, we had to create methods that would parse through the Treehouse API, take a collection of all a user’s badges, and iterate those badges through our dictionary.

  def check_star_requirement(th_json)
    #check json of badge names on profile
    badges = th_json["badges"].collect { |badge| badge["name"] }
    completed_stars_array = @@dictionary.each do |star, requirement|
      star if check_requirements(badges, requirement) 
    end
    completed_stars_array.compact
  end

  def check_requirements(badges, requirement)
    (badges & requirement) == requirement
  end 

The check_star_requirement methodtakes the Treehose json for a user (in my case, teamtreehouse.victoriafriedman.json), iterates through their information on the Treehouse API and collects all their badges. Those badges are saved in an array called badges. Then the dictionary is saved as an array, completed_stars_array and iterated through.

It then calls the check_requirements method, which iterates through the values of the dictionary. If the strings in badges matches any of values in dictionary, then a user will receive that star.

All of this seemed to be working great until we checked our database. Rails “marshaled” our data. An individual entry in our Star table in the Name column, looked like this:

  Aesthetic Foundations
    - Elements
    - Principles
    - Color Theory

Avi pointed us towards the Ruby Marshaling Module. Essentially, Ruby was taking our entire collection, our dictionary, and transforming each key-value pair into a string (which apparently looked like the above example). We were essentially calling, Marshal::Dump, which saves the data and returns the original string. Because the each method also just returns the original string, our iteration wasn’t just saving the key, Aesthetic Foundations, to our database, but the entire string.

Our solution to this problem was really simple, essentially we replaced each with collect. Collect returns the new array, so in our case, it returns an array of key values in the dictionary, but only the key where values are all contained in the badges array.

Deleting Crontab System Mail

| Comments

Last week, I presented an app to NYC on Rails. The main focus was to learn about ActionMailer, paired with cron jobs and the Whenever gem.

The hardest part of all of it was configuring the cron log to write to the correct files. I was getting permission errors when trying to get cron to write to the log directly in my application. In the end, I managed to configure the crontab to print errors to a directy of my computer.

set :cron_log, "~/log/cron_log.log"

While this gave cron proper permissions and allowed me to debug during development, I ended up 283 system emails on my computer, sent directly to victoria@victoria-miranda-friedman’s-macbook. And I had no idea how to remove them from my root directory.

Every time I entered terminal, I saw this message:

In order to enter your mailbox, type mail. This will display:

The return in terminal clearly tells you Type ? for help., which returns a list of all possible methods to act on your mailbox and its contents

And from here, you get clear instructions on how to delete your mail. To delete one email, enter d 1. If you wanted to delete ten emails, you would enter d 1-10, or in my first attempt d 1-283.

The next thing I learned about cron mail, was that exit, exits you from your inbox, but doesn’t save any changes. quit is the command that saves and exits. And as you can see in the image above, after I quit and then entered my mailbox again, I’m told no mail for victoria

Action Mailer Configurations

| Comments

This week, I started working on a presentation with two other girls, Laura Brown and Ana Becker to present at the NYC on Rails meetup this coming Thursday (March 28). Our app revolves around using ActionMailer. And this was the first time I’ve tried to use the gem.

The documentation for it is really good, and the implementation doesn’t require too many steps. RailsGuides has a great step by step breakdown of the entire process, inluding the steps for generating a Mailer.

All of that was easy. I only wanted to render a default template in my view, and am staying away from user authentication.

My problem fell in the configurations. I had no idea that I had to setup SMTP configurations to send my email. And then once I figured that out, where do I enter my specific configurations.

Step 1:
At first we weren’t getting any errors. It seemed as if our app was sending emails…but no one was getting any of them. The first thing we had to do was edit config/evironments/development.rb. That file contains the line:

  config.action_mailer.raise_delivery_errors = false

which needs to be changed to read:

  config.action_mailer.raise_delivery_errors = true

And then we started to get errors we could work from.

Step 2:
Because we’re using a Gmail account for our gem, we had to configure ActionMailer specifically for that account. The first step to that was to include the following two lines:

config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp

These lines delcares that SMTP will deliver our emails. SMTP stands for Simple Mail Transfer Protocol. This protocol also has a layer of authentication built into it’s functionality

Step 3:
The next step is to declare your specific SMTP configurations.

 config.action_mailer.smtp_settings = {
  :address => 'smtp.gmail.com',
  :port => 587,
  :domain => 'localhost:3000',
  :authentication => :plain,
  :user_name => '<email_address>',
  :password => '<email_password>',
  :authentication => 'plain',
  :enable_starttls_auto => true
}

These configurations state that we’re using Gmail, we’re running our app on localhost:3000, and also includes the email address and password for that account that are associated with the app. The last two lines of the settings handle the authentication of the email account.

And that’s it!

Inheritence

| Comments

One of the big differences between Ruby and other object oriented languages is that a class in Ruby can inherit from one and only one class. Essentially, each class can only have one parent, but many children.

A great example to understand basic inheritence is to think about it in terms of animals. A cat is a mammal. And all mammals are animals. To break this down in Ruby, that inheritence would look like this:

class Animal
end

class Mammal < Animal
end

class Cat < Mammal
end

The < denotes inheritence. In this example, the class Cat inherits all the properties from the Mammal class, as well as the Animal class.

class Animal

  def breathe
    "inhale"
  end
end

class Mammal < Animal

  def hair
    "Mammals are the only category of animals that have true hair"
  end
end

class Cat < Mammal

  def meow
    "MEOW"
  end
end

In this case, all instances of the Cat class say “MEOW”, have true hair, and breathe. However, they only inherit directly from Mammal, and Mammal only directly inherits from Animal. No instances of Mammal say “MEOW”.

Another great way to extend functionality to a class in Ruby is through the use of Modules.

A Module is a collection of methods and constants. A module is made up of resuable code that doesn’t naturally form a class. Because it is not a class, a module can’t have instance methods.

Modules allow you to implement mixins. A mixin is a way to either include or extend the functionality of your Module to mulitple Ruby classes.

When you Include a module in a class you are including the module methods as instance methods of that class. When you Extend a module in a class, you are adding the module methods as class methods. Essentially, when you declare extend in your classes, you are saying self.extend.

I found a great example of this functionality in action via Ruby Source.

module Logging
  def logger
    @logger ||= Logger.new(opts)
  end
end

class Person
  include Logging
    def relocate
      logger.debug "Relocating person..."
        # do relocation stuff
    end
end

In this example, the Logging module provides an instance of a logger (@logger). Because class Person includes the Logging module, all of it’s methods are mixed-in as instances methods. The method logger is now a method that acts on all instances of the Person class.

Another option is to extend the Logger module:

  module Logging

    def logger
      @@logger ||= Logger.new(opts)
    end

  end

  class Person
    extend Logging

      def relocate
        Person.logger.debug "Relocating person..."

        # could also access it with this

        self.class.logger.debug "Relocating person..."

      end
    end

In this example, the Logger module as a class variable @@logger which allows this module to be extended to multiple classes. Because the module is extended to the class Person, the method defined in the module can only be called on the class itself, here it is demonstrated in two ways:

Person.logger.debug

and

self.logger.debug

    Helpful Resources:

  1. Inheritence: Ruby Learning
  2. Modules: The Pragmatic Programmer’s Guide
  3. More Modules: Ruby Documentation