Parsing URLs

I wanted to parse a URL and remove any ‘www’ type prefixes and just get the raw domain name.

RUBY

require 'uri'
 
def domain_name(url)
  #remove the http:// with URI.parse
  base_url = URI.parse(url).host
 
  #base_url.split returns an array, ex. ["www", "cnet", "com"]
  url_array = base_url.split('.')
 
  #url may be www.example.com or example.com
  if url_array.count == 3
    url_array.shift
    url_array.join('.')
  elsif url_array.count == 2
    base_url
  end 
end
 
p domain_name('http://www.cnet.com')    #=> "cnet.com"
p domain_name('http://httpbin.org')     #=> "httpbin.org"
p domain_name('http://mail.google.com') #=> "google.com"

JAVASCRIPT

function domainName(str){
  var baseURL = str.split("http://")[1];
  var urlArray = baseURL.split('.');
 
  if (urlArray.length == 3){
    urlArray.shift();
    return urlArray.join('.');
  }
  else{
    return baseURL;
  }
}
 
domainName("http://www.cnet.com");    // "cnet.com"
domainName("http://httpbin.org");     // "httpbin.org"
domainName("http://mail.google.com"); // "google.com"

Why you should switch to Pry from IRB

I first heard about Pry as a replacement for IRB from this post by Jack Kinsella. I wasn’t impressed when I first read about it until I found a helpful feature that really interested me.

 

Pry

[1] pry(main)> arr = Array(1..5)
=> [1, 2, 3, 4, 5]

IRB

irb(main):001:0> arr = Array(1..5)
=> [1, 2, 3, 4, 5]

 

If you’re new to Ruby, unfamiliar with the language, or just curious as to what methods you can call what would you do next? Search the documentation? Google search? Or…

 

[2] pry(main)> cd arr

[3] pry(#):1> ls
Enumerable#methods:
all? collect_concat each_entry each_with_object find_all group_by max min minmax_by partition sort_by
any? detect each_slice entries flat_map inject max_by min_by none? reduce
chunk each_cons each_with_index find grep lazy member? minmax one? slice_before
Array#methods:
& []= compact drop find_index insert pack reject rindex shuffle take uniq!
* assoc compact! drop_while first inspect permutation reject! rotate shuffle! take_while unshift
+ at concat each flatten join pop repeated_combination rotate! size to_a values_at
- bsearch count each_index flatten! keep_if pretty_print repeated_permutation sample slice to_ary zip
<< clear cycle empty? frozen? last pretty_print_cycle replace select slice! to_h |
<=> collect delete eql? hash length product reverse select! sort to_s
== collect! delete_at fetch include? map push reverse! shelljoin sort! transpose
[] combination delete_if fill index map! rassoc reverse_each shift sort_by! uniq
self.methods: __pry__
locals: _ __ _dir_ _ex_ _file_ _in_ _out_ _pry_

 

Yes! You can navigate an object as if you were navigating your file directory from the command line using familiar commands like ‘cd’ and ‘ls’.

With the pry-rails gem you can make pry the default console for your rails app instead of IRB.

Here I have a class ‘Widget’ and call the #all method.

 

[5] pry(Widget)Widget.all
Widget Load (0.4ms) SELECT "widgets".* FROM "widgets"

  Widget Load (0.4ms)  SELECT "widgets".* FROM "widgets"
=> [#<Widget id: 1, serial_number: "123456789", order_id: nil, created_at: "2014-08-19 20:41:52", updated_at: "2014-08-19 20:41:52">]

 

Then:

*assign a widget to a variable ‘w’
*navigate into it using the ‘cd’ command
*list the available methods using the ‘ls’ command (only some are listed here).

 

[6] pry(Widget):1> w = Widget.find(1)
Widget Load (0.3ms) SELECT "widgets".* FROM "widgets" WHERE "widgets"."id" = ? LIMIT 1 [["id", 1]]

=> #

[7] pry(Widget):1> cd w

[8] pry(#):2> ls
ActiveRecord::Core#methods:
<=> connection_handler eql? frozen? hash inspect readonly? slice
== encode_with freeze has_transactional_callbacks? init_with readonly! set_transaction_state
ActiveRecord::Persistence#methods:
becomes decrement delete destroyed? increment! persisted? toggle! update! update_attributes update_column
becomes! decrement! destroy! increment new_record? toggle update update_attribute update_attributes! update_columns
ActiveRecord::Scoping#methods: populate_with_current_scope_attributes
ActiveRecord::Sanitization#methods: quoted_id
ActiveRecord::AttributeAssignment#methods: assign_attributes attributes=
ActiveModel::Conversion#methods: to_model to_partial_path
ActiveRecord::Integration#methods: cache_key to_param
ActiveModel::Validations#methods: errors invalid? read_attribute_for_validation validates_with
ActiveSupport::Callbacks#methods: run_callbacks
ActiveModel::Validations::HelperMethods#methods:
validates_absence_of validates_confirmation_of validates_format_of validates_length_of validates_presence_of
validates_acceptance_of validates_exclusion_of validates_inclusion_of validates_numericality_of validates_size_of
ActiveRecord::Validations#methods: valid?
ActiveRecord::Locking::Optimistic#methods: locking_enabled?
ActiveRecord::Locking::Pessimistic#methods: lock! with_lock
:

What is the significance of December 31, 1969?

I was fooling around with the Time class in Ruby and figured out I could convert the current time to an integer.

Integer(Time.now)
=> 1408000367

I casually noticed it wasn’t a random number being generated, that it seemed to be some sort of counter…in seconds. That led me to the inevitable…

Time.at(0)
=> 1969-12-31 16:00:00 -0800

December 31, 1969 at 4pm (PST) or January 1, 1970 (UTC). It led me on a sort of wild goose chase. WHY exactly is midnight January 1, 1970 being used as the zero hour? From the Ruby doc:

Time is stored internally as the number of seconds with fraction since the Epoch, January 1, 1970 00:00 UTC. 

What’s an “Epoch”?

the beginning of a distinctive period in the history of someone or something.

Okay, so we’re back at my original question, “WHY exactly is midnight January 1, 1970 being used as the ‘epoch’?”

Wikipedia, can you help?

The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601). There is a problem with this definition, in that UTC did not exist in its current form until 1972

Oh boy…How about Stack Overflow?

 The programmers chose the arbitrary date of January 1, 1971 GMT to be epoch time. This was partly due to the fact that older computers couldn’t handle large numbers so the date had to be in the recent past. Afterwards, epoch time was adjusted to be Jan 1, 1970 so as to be a nice, round number.

So basically, nothing “happened” on that date. It was an arbitrary date chosen based on the original time of the work being done.

Ahh, that sounds about right.

Order Management – A new project I’m working on

Before I got hired I was using Rails 4 exclusively, but on the job we were using Rails 3. I thought it would be a good idea to keep up on the latest and greatest so I decided to start a new Rails 4 project.

I started a mock order management system (link to github) and I’m trying to do things the “right way” in the Ruby/Rails sense. By “right way” I mean TDD and planning things like a PROFESSIONAL DEVELOPER and not like a PROGRAMMER. It’s definitely a different way of approaching a problem…and I LIKE IT.

Planning things out with diagrams and using TDD “feels” slower for now because I’m not used to doing it. But what I’m gaining is the ability to step away from a project for a break, then come back and being able to easily pick up where I left off because I’ve planned out the steps.

Thwack – A cool game I made

Link to files on Github

A very simple fighting game.

You will select two warriors, and equip them with a weapon and armor.

Warrior Classes

* Barbarian - Strong, but not agile
* Knight - Blend of strength and agility
* Ninja - High agility, but low strength

Weapon Classes

* Club - Heavy damage, decreases agility
* Katana - Medium damage, no effect on agility
* Dagger - Low damage, increases agility

Armor Classes

* Iron Armor - Decreases agility, increases defense
* Bronze Armor - No effect on agility or defense
* Leather Armor - Increases agility, decreases defense

Player Attributes

HP - Hit points/health
STR - Strength/Attack Damage
DEF - Defense
AGI - Agility (affects chance of an attack connecting)

Gameplay

The basic formula is DMG = (ATK - DEF). The game continues until one player has been killed.

Files

* thwack_init.rb = Main gameplay script
* thwack_combat.rb = fight and defense algorithms

* thwack_armor.rb = Armor classes
* thwack_weapon.rb = Weapon classes

* thwack_barbarian.rb = Barbarian warrior classes
* thwack_knight.rb = Knight warrior classes
* thwack_ninja.rb = Ninja warrior classes

Link to files on Github