Wednesday, July 9, 2014

Parse JSON in Ruby in 10 simple steps

1. Get a JSON Endpoint. You know you want one.

2. Map the JSON file by running your RUBY Interpreter (like pry or erb) and requiring the gems "awesome_print" & "HTTParty" in order to see the JSON file structure. Try your HTTParty.get() request without the awesome_print if you don't believe me, you will return data but it won't be easy to read.

3. In your Ruby Interpreter uri = "https://data.cityofnewyork.us/api/views/he7q-3hwy/rows.json"

4. parsed = HTTParty.get(uri). Congratulations you have a human readable JSON file now.

5. now type 'parsed.keys' In order to find the top level areas of your file. In this case you get "meta" & "data"... and a lot of other json stuff. 'Meta' is just crap and 'data' is what holds the actual valuable information.

6. Continue the pattern by typing in 'parsed["data"].keys' which returns a failure message telling you its an array, bingo! Do you like being careful? Type 'parsed['data'].class to make sure what kind of data you are dealing with at first.

7. type 'parsed["data"].length', which returns a lot of info in there. It must be valuable, eh? Proove it!

8. Lets check one at random. Type 'parsed["data"].sample'

9. Lets check the one at index [0]. Type 'parsed["data"][0]'. You see a bunch of stuff don't you? Some of it is garbage, some seems rather valuable, but all are separated by commas. Do you remember how to count? Good, 'parsed["data"].sample[0]' returns the first entry, but in this case that is probably just the ID, what we really want is entry [9] & [10], the 10th and 11th entries in each Array. 10. Too lazy to count? Good, let's use rubys each_with_index method in order to take each value and assign it an number, like so:

parsed["data"].sample.each_with_index {|value, index| puts "#{index}: #{value} " }

Monday, July 7, 2014

MongoDB Intro

db.cars.remove( {"_id" : allCars[3]["_id"]} ) db.cars.find() db.cars.update( {"_id" : allCars[2]["_id"]}, {$set : { "dog_friendliness" : true } } ) db.cars.find() "_id" "make" "name" "color" db.cars.insert({ "make" : "Nissan", "name" : "Leaf", "color: "Yellow" }) //new car is made db.cars.find( { "make" : "Nissan", "dog_friendliness" : true }

Tuesday, June 24, 2014

erase PSQL databases

Its Spring Cleaning time so go through and cleanup your databases, from prompt:

$ drop db database_name_development
$ drop db database_name_test
$ drop db database_name_production 

Reboot PSQL,
# \l and they are gone


Monday, June 23, 2014

Intro to Rails Roadmap

Let's get some background info about what we can do.
$ rails
$ rails new --help
Let's go ahead and create your app. Specify PSQL database, and skip the Spring Gem because it crashes some important things which we will go over later. Honestly this tutorial is based on: https://github.com/zackn9ne/WDI_NYC_Apr14_String/tree/master/w08/d02/Zack_Levine/railer-ajerx/single_crud
$ rails new myapp --database=postgresql --skip-spring
Edit your config/database.yml file as follows for most basic of operations, and watch your indenting its a YML file:
default: &default
  adapter: postgresql
  pool: 5
  timeout: 5000
 
development:
 first_rails=""
Bundle all the GEM's in the Gemfile and, then exec the command rake db:create:all.
$ bundle exec rake db:create:all
A quick check to make sure everything runs.
$ rails s 
Now let's make our models. Planet----- name:string image:string* we'll go ahead and expect a URL here diameter:integer life:boolean
$ rails g model Planet name:string image:string life:boolean weight:integer
Commit this initialisation by raking!
$ rake db:migrate
Now fix your routes at
config/routes.rb
1. change the rails splashpage to this 2. run rake:routes to do some automagic routes
root "cars#index"

resources :cars

Make your controller file based on the Model you made earlier

-The naming convention for this is "model_controller.rb" -A hint is to $ rake routes, copy down the aspects on the far right, and iterate through them as methods to use this as a checklist in your controller file!

Try to run your server, your gonna get a no view error

-Switch to views/ and $mkdir /controller (from the name above in plural format) -touch an index.html.erb file in there

Go back to your specific Controller file and add the CRSF prevention stuff

 private
 def car_attributes
#whiteliste, but these come out as a variable called car_attributes that the sysop can use only
  params.require(:car).permit(:year, :make, :model, :color)
 end

Let's do some Rails Console Work to Seed some test values

Boot up the Rails Console and get to work.
Here you want to make a Car.new with some whitelisted params. Then check the car you just made by calling it and one of its freshly made params.
Brush up on your ActiveRecord Skills for this one.
> car1 = Car.new(model: "some", make: "bitchin ride")
> car1.model
> car1.save
Alternatively
> car1 = Car.create(model: "some", make: "bitchin")

Go to your Views Folder

Let's remember to setup views for each model on an equal directory level as <code>app/views/layouts</code>, eg <code>app/views/cars</code>. Check $ rake routes. It will imply the Controller#Action as folows:

  • index.html.erb
  • create.html.erb
  • new.html.erb
  • edit.html.erb
  • show.html.erb
  • update.htmlerb
  • destroy.html.rb

Check your schema.rb in order to setup your Rails Form Helper file. Here you will get a list of the parameters you can send to the DB.

Now you are going to have all the views based on rake routes, and in addition please go to the db/schema.rb file in order to especially see the available fields in your new.html.erb (in this case) file. 

Rails Form Helpers are just like include files. They must be named _something.html.erb (in this case because we are using erb). Here is some code for one.

is the partial %>
<%# This is the partial %>
<%# This is the partial %>
<%# This is the partial %>

New Car

<%= form_for(@car) do |f| %> #url was cars_path #starts the loop for the model name, again cars_path means Prefix of cars GET part and go there, this partial GIVES the @car instance to edit.html.erb, or where it happened to be called <%# params.require(:car).permit(:year, :make, :model, :color) %> <%# form helpers %> #starts creating the attributes allowed from private in controller <%= f.text_field :make, { placeholder: "car make" } %> <%= f.text_field :model, { placeholder: "model" } %> <%= f.text_field :year, { placeholder: "car year" } %> <%= f.text_field :color, { placeholder: "car color" } %> <%= f.text_field :image, { placeholder: "image url" } %> <%= f.button :submit %>
In your new.html.erb call the Form Helper

Create an object

<%= render partial: "form", locals: { car: @car } %> <%# you are telling the forthcoming partial that your are using the car object you created in the new conteroller %>

Let's Get Some Sample Data

db/seeds.rb
SubwayLine.create(name: "L", color: "yellow")

stations = HTTParty.get("https://data.cityofnewyork.us/api/views/he7q-3hwy/rows.json")

stations["data"].each do |station|
 db_station = Station.create({
  address: station[9]
  })
 subway_line_names = station[10].split("-").select {|name| SubwayLine.find_by(name: name)}
 subway_line_names.each do |line_name|
  Stop.create({
   station_id: db_station.id,
   subway_line_id: SubwayLine.find_by(name: line_name).id
   })
 end
end
$ rake g models todos completed:boolean
$ rake db:create

basic Ruby and RSync tutorial post

This is how to test with RSpec This page was formatted via http://alexgorbatchev.com/SyntaxHighlighter/ Go into your shell and setup your environment.
$ mkdir my-testing-project/
$ rspec --init
Make your files, name your test file with a '_spec' suffix or rspec will hate you.
$ touch lib/app.rb
$ touch spec/tester_spec.rb 
Open your tester.rb
require 'app'
RSpec.describe(Class) do

 ## these look vaguely like english thats why
 it("should existy probably") do
  expect(Hangman.new).to(be_a(Hangman))
 end

end

Take a break, when you are done go into your app directory shell and run the following:
$ rspec
lib/ #a conventional place for all_ruby_source_code.rb
lib/the_source_file.rb
spec/ #a conventional place test_all_ruby_soruce_code_spec.rb
spec/test_the_source_file.rb

###
insdie spec/tester_file.rb
###
require 'the_source_file'
RSpec.describe(Class) do
 
## these look vaguely like english thats why
it("should existy probably") do

expect(Hangman.new).to(be_a(Hangman))

 end



end