Ruby On Rails: An Introduction - GitHub Pages

2y ago
43 Views
2 Downloads
541.93 KB
27 Pages
Last View : 7d ago
Last Download : 3m ago
Upload by : Baylee Stein
Transcription

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass NotesRuby on Rails: An IntroductionCourse Highlights: WEEK 1 – Welcome and Setting up the Development Environment1.1 Course Introduction Great for rapid development Able to rapidly prototype Twitter uses RoR Course 1o Basic flow of how information comes ino Functional application Course 2:o How you interact with DB Course 3:o Really dives in on this and how you interact well with MongoDB and RoRo Implementation of NoSQL DB Course 4:o RESTApi is used commonly (FB, Twitter)o Full stack web developer – service side could be great, but we still need to careabout the client facing side, i.e. frontendo User interaction needs to be perfecto HTML, CSS, JavaScript – design and turn it into real website Course 5:o AngularJS addresses a ton of the issues with front end web devo Helps to make things fastero You’ll be able to build a full website where majority of lift is on client side Capstone: which I’m not going to do reallyModule 1: Setting up the Dev Env 3 topicso Software installation§ Installation of Ruby and RoRo Coding editors§ Probably sublimeo Git§ Duh VCS§ Going to deploy to the cloud§ Going to be helpful when deploying an applicationRemote Repos and Github

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes Linke remote repo with your local repoo Git remote add alias remote urlorigin – default alias for a cloned repoMost of this is default gitWEEK 2 – Introduction to Ruby2.0 Getting to Know Ruby2.0.a Ruby Basics Historyo Invented by Yukihiro Matsumotoo Popularized by Ruby on Rails framework Dynamic, OO, Elegant, expressive, and declarative Designed to make programmers happy So like this is going to be iterating over something three times:o 3.times Ruby basicso # to commento 2 space indentation for each nested levelo Everything is evaluated Printing to consoleo puts§ print string to console; as in put stringo p§ Prints out internal representation of object – great for debugging. Variableso snake case Constantso ALL CAPS or FirstCap Classes (and Modules)o CamelCase Semicolonso Don’t need them. Don’t include them. Extremely expressive2.0.b. Flow of Control if / elsif/ elseo No parentheses or curly raceso Use end to close flow control blocko case until / unless?

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso unless – basically, if something is not equal to something else§ essentially like a not equal too until – opposite of while; executes until a condition is metwhile / forTriple equalsFlow of control: modifier form (meaning a ton of stuff on one line)Only things that are false are:o nil objecto false objectTriple equalso Use double equal most of the timeo Equal in its own wayo Special kind of equalso You can use this with regexCase expressionso Similar to a series of if statements§ age 21o caseo when age 21oputs o when 1 0oputs o Specify a target next to case and each when clause is compared to target§ So like§ Name ‘Fisher’§ case name§ when # comparison to name§ when # comparison to nameo No fall through logico The only case that actually matches gets executedFor loopo for i in 0.2o puts io endo but most commonly, each / times preferred2.0.c. Functions Functions/methodso Function is defined outside of a classo Method is defined inside a classo However, in Ruby they are all methods Methods

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso Parentheses are option when defining and calling a methodo Used for clarityNo need to declare type of parametersReturn keyword is optional – last executed line is returnedExpressive method nameso Method names can end with:§ ? – predicate methods (normally return boolean values)§ ! – dangerous side effectso Also note: number.zero is a methodDefault argumentso Pretty simpleo def factorial with default(n 5)§ n 0 ? 1 : n * factorial with default(n-1)o endSplato * prefixes parameter insideo Can apply to middle parameter or any one2.0.d Blocks Basically, chunks of code that get executed Enclosed between either curly braces {} or the do and end blocks Passed in as the last argument Conventiono Use {} when block content is single lineo Do and end when block content spans multiple lineso Often used as iterators Exampleso 1.times { puts “Hello World!”}o 2.times do index o if index 0oputs indexo endo end Coding with blockso Implicit:§ Use block given? to see if block was passed in§ Use yield to “call” the block§ Ex: def two times implicit return “No block” unless block given? yield yield

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes endo Explicit:§ Use & in front of the last parameter§ Use call method to call block§ Ex: def two times explicit (&i am a block) return “No block” if i am a block.nil? i am a block.call i am a block.call end§ Explicit is a little more directSummaryo Just code that you can pass into methodso Can either use blocks implicitly or explicitly2.0.e Files Reading from Fileo File.foreach(‘test.txt’) do line o puts lineo p lineo p line.chomp # chomps off newline character at the end of the lineo p line.split # array of words in line Reading from Non existing fileo You would get an error pretty much immediatelyo Stops execution Handling Exceptionso Begino File.foreach( ‘do not exist.txt’ ) do line oputs line.chompo endo rescue Exception eo puts e.messageo puts “Let’s pretend this didn’t happeno end Alternative to Exceptionso if File.exist? ‘test.txt’o File.foreach(‘test.txt’) do line oputs line.chompo endo endo This is good for very simple cases Writing to a File

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o File.open(“test1.txt”, “w”) do file o file.puts “One line”o file.puts “Another”o endEnvironment variableso puts ENV[“EDITOR”]Summaryo Files automatically closed at the end of the blocko Either use exception handling or check for existence of the file before accessing2.1 Collections and String APIs2.1.a Strings Stringso Single-quote literal strings are very literalo Allow escaping of ‘ with \o Show almost everything as iso Double quoted strings interpret special characters like \n and \to Allow string interpolation Strings / Interpolationo single quoted ‘ice cream \n followed by it\’s a party!’o double quoted “ice cream \n followed by it\’s a party!”§ this will show the newline Interpolation is only avaialable for double-quoted stringso def multiply (one, two)o “#{one} multiplied by #{two} equals #{one * two}”o endo This converts the entire thing to a string and also does the computation More stringso String methods ending with ! modify the existing string§ Most others just return a new stringo Can also use %Q{long multiline string}§ Same behavior as a double-quoted string Exampleo My name “ tim”o Puts my name.lstrip.capitalize # Timo P my name # “ tim”o My name.lstrip! # destructive! Removed the leading spaceo My name[0] ‘K’o Puts my name # Kimo Cur weather %Q{it’s a hot day outsidegrab your umbrellas }o Cur weather.lines do line

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso line.sub! ‘hot’, ‘rainy’ # substitute ‘hot’ with ‘rainyStrings APIo include? other stringSymbolso :foo – highly optimized stringo Constant names that you don’t have to pre-declareo “Stands for something” string typeSymbols (cont)o Guaranteed to be unique and immutableo Can be converted to a String with to so Can convert from String to Symboll with to symSymbol can be representation of a method nameSymbols and Strings are similar you must determine which makes more sense to useSummaryo Interpolation lets you finish your thougtho Strings have a lot of really useful API2.1.b Arrays Arrayso Collection of object references (auto-expandable – no fixed size)o Indexed using []o Can be indexed with neg numbers or rangeso Heterogeneous types allowedo Can use %w{str1 str2} for string array creation Exampleso arr words %w{ what a great day today! }o puts arr words[-2] # dayo puts “#{arr words.first} - #{arr words.last}” # what – today!o p arr words[-3, 2] # [“great”, “day”] (go back 3 and take 2)o p arr words[2.4]o can also do join Modifying Arrayso Append: push or o Remove pop or shifto Randomly pull elements out with sampleo Sort of reverse with sort! and reverse!§ sort without exclamation returns a new copy of the array Exampleso # You want a stack?o stack []; stack “one”; stash.push (“two”)o puts stack.pop # twoo # you want a queue?

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso Queue []; queue.push “one”; queue.push “two”o Puts queue.shift # oneo If you specify and insert into an index that is beyond the range, it’s going tocreate nils for everything elseOther Array Methodso each – loop through array§ takes a blocko select – filter array by selecting§ takes a blocko reject – filter array by rejecting§ pretty much the opposite of the one aboveo map – modify each element in the array§ maps every element to a new element based on the block passed inImportant api: http://ruby-doc.org/core-2.2.0/Array.htmlExampleo a [1, 3, 4, 7, 8, 10]o new arr a.select { num num 10}.reject { num num.even?}o p new arr # [1,3,7]Summaryo Arrays API is very flexible and powerfulo Lots of ways to process elements2.1.c Ranges Used to express natural consecutive sequences 1.20, ‘a’.’z’ Two main ruleso Two dots à all-inclusive§ 1.10 (1 is included, 10 is included)o Three dots à end-exclusive§ 1 10 (1 is included, 10 IS EXCLUDED)o The more dots you have, the less you have at the end Rangeso Very efficiento Only start and end storedo Can be converted to an array with to ao Used for conditions and intervals Exampleso puts (1 10) 5.3 # trueo puts (‘a’ ’r’) “r” # false, end –exclusive Summaryo Useful for consec sequences

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso Convert a range to an array for more functionality2.1.d Hashes Hasheso Indexed collection of object referenceso Created with either {} or Hash.newo Also known as associative arrayso Index(key) can be anything§ Not just an int as is the case with arrayso Accessed using []o Values set using§ (creation)§ [] (post creation) Exampleo editor props { “font” “Arial”, “size” 12, “color” “red}o editor props.length Hasheso Accessing a value in the Hash for which an entry does not existo nil is returnedo BUT if you create a Hash with Hash.new(0), then 0 is going to be returnedinstead. Exampleo word freq Hash.new(0)o sentence “Chicka chicka boom boom”o sentence.split.each do word o word frequency[word.downcase] 1o end More hahseo The order of putting things into Hash maintainedo If using symbols as keys, can use symbol: syntaxo If a Hash is the last argument to a method, you can drop the curlies Block and Hash Confusiono a hash {:one “one”}o puts a hasho # can’t do puts { :one “one”}o # ruby gets confused and think it’s a blocko To get around this you can use parenthesiso Or you can just drop the blocks all together2.2 Object Orientated Programming in Ruby2.2.a Classes OO Review

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso Identify things your program is edaling witho Classes are things (blueprints)§ Containers of methodso Objects are instances of those thingso Objects contain instance variables (state)Instance variableso Begin with @o Not declared§ Spring into existence when first usedo Available to all instance methods of the classObject creationo Classes are factories§ Calling new method creates an instance of class§ new causes initializeExampleo class Persono def initialize (name, age) # constructoro@name nameo@age ageo endo def get infoo@additional info “Interesting”o“Name: #{@name}, age: #{@age}”o endo endAccessing Datao Instance variables are private§ Cannot be accessed from outside th4e classo Methods have public access by defaulto To access instance variables, need to define getters/setterExampleo def nameo @nameo endo def name (new name)o @name new nameo endEasier syntax for accessing datao attr accessor – getter and settero attr reader – getter onlyo attr writer – setter onlyExample

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o class Persono attr accessor :name, :ageo endSometimes we want to use a more intelligent constructorSelfo Inside instance method, self refers to the object itselfo Usually using self for calling other methods of the same instance is extraneouso Sometimes using self is requiredo Outside instance method def, self refers to the class itselfSummaryo Objects are created with newo Use the short form for setting/getting datao Don’t forget self when required2.2.b Class Inheritance operator evaluates the left side; if true, returns it, else it returns the right side @x @x 5 will retrun 5 the first time and @x the next time short formo @x 5 This is really helpful for setting an instance variable to something the first time Class Methodso Invoked ON the class (as opposed to an instance of the class)o Self OUTSIDE of the method definition refers to the Class objecto Three ways to define class methods§ Class variables begin with @@ Exampleo class MathFunctionso def self.double(var)otimes called; var * 2o endo class selfodef times calledo@@times called 0; @@times called 1oendo endo endo def MathFunctions.triple(var)o times called; var * 3o end Class Inheritanceo Every class implicitly inherits from Objecto Object inherits from BasicObject

o No multiple inheritance§ Mixins are used insteado Class SmallDog Dogo Def barko“barks quietly”o endo endJohn Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes2.2.c Modules Moduleo Container for classes, methods, and constants (or other modules)o Like a Class but cannot be instantiated Module as Namespaceo module Sports§ class Match attr accessor :score§ endo endo module Patterns§ class Match attr accessor :complete§ endo endo match1 Sports::Match.newo match2 Patterns::Match.new Module as Mixino Interfaces in OOo Contract defines what a class could doo Mixins provide a way to share ready code among multiple classes Exampleo module SayMyName§ attr accessor :name§ def print name puts “Name: #{@name}”§ endo endo class Person§ include SayMyNameo endo person Person.newo person.name “Joe”o person.print name # Name:joe

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes Enumerable Moduleo map, select, reject, detect, etco Used by Array class and many otherso Provide an implementation for each methodo And then you can include it in your own classExampleo class Player§ attr reader :name, :age, :skill level§ def initialize (name, age, skill level) @name name @age age @skill level§ end§ def to s “ #{name}: #{skill level}(SL), #{age}(AGE) ”§ endo endEnumerable in Actiono require relative ‘player’o require relative ‘team’Modules allow you to mixin useful code into other classesRequire relative is useful for including other ruby files relative to the current ruby code2.2.d Scope Methods and classes begin new scope for variables Exampleo v1 “outside”o class MyClasso def my methodop v1 # exception thrownop local variables # prints out a list of all the local variableso end Scope constantso Pretty intuitive Scope blocko Blocks inherit outer scopeo Block is a closure§ Remembers the context in which it was defined and then uses thatcontext whenever Block – local scopeo A variable created inside the block is only available to the blocko Params to the block are always local to the block

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes2.2.e Access Control Three levels of access control Controlling access How private is private access? Access controlo When designing, how much do you want to expose?o Encapsulation: try to hide the internal representation of the object so you canchange it latero Three levels§ Public§ Protected§ Private Specifying access controlo Two ways§ Specify public projected or private Everything until the next access control keyword will be of thatlevel§ Define the methods regularly and then specify public, private, protectedaccess level and list the comma separated methods under those levelsusing method symbolso Example§ class MyAlgorithm§ private§def test1§“Private”§end§ protected§def test2§“Protected§end§ endo Example 2§ class Another§ def test1§“Private, as declared later”§ end§ private :test1§ endo Access control meaning§ Public methods – no access control is enforced§ Protected methods – can be invoked by the objects of defining class or

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes§ subclassesPrivate methods – cannot be invoked with an explicit receiver Setting an attribute can be invoked with explicit receiverSummaryo Public and private access controls are used the most2.3 Unit Testing with RSpec2.3.a Introduction to Unit Testing Ensure your code works Serves as documentation for devs Refactor to make sure you didn’t break anything Enter Test::Unito Ruby takes testing very seriouslyo Has Test::Unit shipped with ito Ruby 1.9 stripped Test::Unit to a minimumo Member of the XUnit family (Junit, CppUnit)o Basic idea: extend Test::Unit::TestCaseo Prefix method names with testo If one of the methods fails, others keep going (good thing)o Can use setup() and teardown() methods for setting up behavior that willexecute before every test method Exampleo class Calculator§ attr reader :name§ def initialize(name) @name name§ end§ def add(one,two) one – two§ endo Then your testing would look like:§ require ‘test/unit’§ require relative ‘calculator’§ class CalculatorTest Test::Unit::TestCase def setupo @calc Calculator.new(‘test’) end def test additiono asset equal 4, @calc.add(2,2) endo then run ruby calculator test.rbo Also good mneumoic to remember is EACH

§Expected first, then actualJohn Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes2.3.b Introduction to RSpec Testing with RSpeco Test::Unit “does the job” but it would be nice if tests would be more descriptive,more English-likeo The writing of the tests is more intuitive as well as the output from running thetests Installingo Easy gem install rspec describe()o Set of related tests (a.k.a. example group)o Takes either a String or Class as an argumento All specs must be inside a describe blocko No class to subclass before() and after() methodso before and after methods are similar to setup and teardowno Can pass in either :each or :all (infreq used) to specifyc whether the block willrun before/after each test or once before/after all testso before :all could be useful if you only want to connect to DB once it()o Main logic happens inside the it() method Exampleo require ‘rspec’o require relative ‘./calculator’o describe Calculator do§ before { @calculator Calculator.new(‘RSpec calculator’)}§ it “should add 2 numbers correctly” do expect(@calculator.add(2,2)).to eq 4§ end§ it “should subtract 2 numbers correctly” do expect(@calculator.subtract(4,2)).to eq 2§ endo end Summaryo RSpec makes testing more intuitive2.3.c RSpec Matchers Hands to and not to methods on all outcome of expectations to()/not to() methods take one parameter – a matchero be true / be falseo eq 3

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o raise error(SomeError)be predicate – booleano If the object on which the test is operating has a predicate method, you auto getthe be predicate matchero Be nil is a valid matcher because every predicate method has a :nil? MethodWEEK 3 – Introduction to Ruby on Rails3.0 Core Concepts3.0.a Welcome to Module 3: Introduction to Ruby on Rails Core principles Model View Controllero Principle that applies to a lot of web frameworks as well Convention Over Configurationo Following conventions helps applications be built very quickly3.0.b Introduction to Rails Framework for making dynamic web applications Dynamico Content that is gotten from a database or something like thato Html is just going to be static (i.e. not dynamic)o Created by David Heinemeier Hansson§ Also a racecar driver Who is Using Rails?o Huluo Twittero Githubo White pages Why use Rails?o Convention Over Configuration (COC)o Less code to writeo Learn it once and then know what to expect the next time Why Use Rails?o Database Abstraction Layero No need to deal with low-level DB detailso No more SQL (Almost)o ORM§ Object Relational Mapping§ Abstracting the code to interact with DB using Ruby§ Mapping your database to your Ruby Classes Why else?o Agile-friendlyo DRY principle

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o Cross-platformSQLiteo Rails uses SQLite for database by defaulto Self-contained, serverless, zero-configuration, transactional, relationsal SQLdatabase engineo Claim: Most widely deployed SQL database engine in the worldMVC: Model View Controllero Well-established software pattern used by many web and desktop frameworkso Separation of concernso Model – represents the data the application is working with (and poss businesslogic)o View – representation of that data (visually)o Controller – interaction between model and viewMVC CycleoSummaryo Rails is good with RAPID PROTOTYPINGo MVC and COC enable you to think less and do more3.0.c Creating your First Application How to create and run your app Directory structure (CoC) Adding static pages to your application Creating First App

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o rails new appnameo rails new –h for more operationso runBundler (gems manager)o Cleans up the house and resolves dependency issuesVersion Control Your Rails Appo Rails automatically generate .gitignore inside repoo cd my first appo git inito git add .o git commit –m “Initial commit”Running the Appo Rails alos provides a built-in web servero rails serverRunning the App (cont)o Good at holding your hando 1 use bin/rails generate to create your models and controllerso 2 set up a root route to replace the default placeo 3 Configure your databaseDirectory Structure Conventiono app/ directory – controllers, views, models, helpers (most of the time)o config/ - which database are you going to be using (and username and password)o db/ - files related to your db and migration scripts (how to change from onedatabase to another)o public/ - static files. Html files. All that boring shit.o Gemfileo Gemfile.lock – dependencies managed by Bundlerpublic/hello static.htmlo Server looks into public directory before looking anywhere elseo So if we want to add a completely static web page to our application – we canadd it under public directory3.0.d Controller and View How to generate controller Actions Embedded Ruby (ERB) Generating a Controllero Controllers contain actions (Ruby methods) and orchestrate web requestso Rails can quick generate a controller and 0 or more actions with associated viewso rails generate controller controller name [action1 action2] Generating a Controller Exampleo rails g controller greeter hello

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes ERB (Embedded Ruby)o Looks like html but has an .erb extensiono ERB is a templating library (similar to jSP) that lets you embed Ruby into yourHTMLo Two tag patterns to learn:§ % ruby code % - evaluate Ruby code§ % ruby code % - output evaluated Ruby codeo Whole point is to mix html static and Ruby codeNew hello.html.erbo % random names [“Alex”, “Joe”] % o h1 Greetins, % random names.sample % /h1 o p The time now is % Time.now % /p 3.0.e Routes Routing Rake How to analyze current routes Routeso Before the controller can orchestrate where the web request goes, the requestneeds to get routed to the controllero The route for hello action was auto generated with the rails g controller MVC(R) Cycle oroutes.rb

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso All the routes need to be specified in the config/routes.rb fileo Let’s add the route for the goodbye actiono It’l look like§ Rails.application.routes.draw do get ‘greeter/hello’ “greeter#hello”o This syntax is saying go to controller / actiono So you can map different things to the name if you do thiso ‘greeter/hello’ ‘greeter#whatsgood’ get ‘greeter/goodbye’Rakeo Ruby’s makeo No XML – written entirely in Rubyo Rails uses rake to automate app-related tasks§ Database, running tests, etco rake –tasksIndividual Rake Tasko Can zero-in on an individual rake task and what it does with –describe flago rake –describe task nameo rake –describe routes§ Print out all defined routes in match order, with names. Target specificcontroller with CONTROLLER xRake Routeso rake routesSummaryo Router directs the request to the right controllero rake routes lets you see which routes are currently defined3.1 Diving Deeper into Rails3.1.a Moving Business Logic Out of View Moving business logic out of View and into Controller in order to comply with MVC Action Methods Inside Controllero If the action (method) is not really doinganything (i.e. empty), we can remove ito As long as there is a proper route defined and there is a properly named viewfile/template, the action method does not have to be there Rails will find thecorrect template by convention Controller: New Looko class GreeterController ApplicationController§ # def hello§ # end§ # def goodbye§ # endo end

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes o This will still work totally findo So what’s the point of having them there?o Business logic does not belong in the ViewMoving Business Logic Outo Instance variables from the controller are available inside the viewo class GreeterController ApplicationController§ def hello random names [“Alex”, “Joe”, “Michael”] @name random names.sample @time Time.now @times displayed 0 @times displayed 1§ endo endInstance Variables in Railso Unlike some frameworks, you cannot “store” values in the controller’s instancevariables in between requestso Alternatives?§ Session (store in the http session)§ Database (store in the database)Summaryo Keep business logic OUT of the viewo Instance variabels in the controller are available to viewo Instance variables do not stick around between requests3.1.b Helpers Helpers and using link to Helperso We’ve made the current time available through @time instance variableo What if we wanted to format that time?§ Should it go into view? (then non-reusable)§ Controller? Should be “view” agnostic Helperso greeter helper.rb module generatedo Let’s add a helper methodo Example§ module GreeterHelper def formatted time(time)o time.strftime(“%I:%M%p”) end§ end§ Available to ALL views

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Noteso Then you can put it in the hello.html.erb fileRail’s Built-In Helpers: link too link to name, path§ Hyperlink generator that displayed the name and linked to the path§ Path could either be a regular string or a route defined in the routes.rbending with url or patho Instead of specifying a path, you specify a variable, automatically changes yourpage if the variable changeso url and path used interchangeable, but according to the spec full path isrequired in cases of redirectionlink to in actiono #in hello.html.erbo p % link to “Google”, “https://www.google.com” % /p o p % link t “Goodbye”, greeter goodbye path % /p o greeter goodbye derived from routes.rb (see Prefix column in rake routes)Summaryo Helpers are “macros” / “formatters” for your viewo When using link to there is no need to change things if a path changes3.2 Building a Ruby on Rails Application3.2.a Introduction to HTTParty Going to look at Ruby gems How to use HTTParty Ruby gem RubyGemso Just a package manager What are Restful Web Services?o Simple web services implemented using HTTP (and principles of REST) that:§ Have a base URI§ Support a data exchange format like XML or JSON§ Support a set of HTTP operations (GET, POST, etc)o Flipping web on it’s heado Thinkg about web as more of an MVC pattern§ Really just stores those resources and you can get it in multiple differenttypes of formats§ Html isn’t great to parse but xml and json are HTTParty Gemo Restful web services client (think your browser)o Browser is just your client from a web servero Automatic parsing of JSON and XML into Ruby hasheso Provides support for§ Basic http authentication§ And default request query params

John Larkin12/28/17Coursera: Ruby on Rails: An IntroductionClass Notes Lots of Restful APIs Out Thereo Every self respecting web service normally has some restful api that it provideso In addition to the htmlo Most popular APIs?§ Facebook§ Google Maps§ Fitbit§ LinkedIn§ Bloomberg§ Twitter§ Instagramo The html is just one of the formats of information that’s stored on websitesHTTParty Usageo include HTTParty moduleo can specify§ base uri for your requests§ default params (API developer key for example)§ format to tell it which format things are coming ino Coursera itself has a Restful APISpecify a q request parameterFirst param is specified by ? and then others specified by &HTTParty Exampleo require ‘httparty’o require ‘pp’ # pretty printo class Coursera§ include HTTParty§ base uri ’§ default params fields: ‘smallIcon,shortDescription’ q: ‘search’§ format :json§ def self.for term get(“”, query: {query: term})[“elements”]§ endo endo pp Coursera.for “python”o Get back a giant hash which has elements as it’s key3.2.b Bundler Provides a consistent environment for Ruby projects by tracking and installing the exactgems and versions that are needed Bundlero Lets you specify gems for

WEEK 2 – Introduction to Ruby 2.0 Getting to Know Ruby 2.0.a Ruby Basics History o Invented by Yukihiro Matsumoto o Popularized by Ruby on Rails framework Dynamic, OO, Elegant, expressive, and declarative Designed to make programmers happy So like this is going to be iterating over something three times: o 3.times Ruby basics

Related Documents:

Note from the Publisher The Ruby on Rails 3 Tutorial and Reference Collectionconsists of two bestselling Rails eBooks: Ruby on Rails 3 Tutorial:Learn Rails by Example by Michael Hartl The Rails 3 Wayby Obie Fernandez Ruby on Rails 3 Tutorial:Learn Rails by Exampleis a hands-on guide to the Rails 3 envi- ronment.Through detailed instruction,you develop your own complete sample

We are installing Ruby On Rails on Linux using rbenv. It is a lightweight Ruby Version Management Tool. The rbenv provides an easy installation procedure to manage various versions of Ruby, and a solid environment for developing Ruby on Rails applications. Follow the steps given below to install Ruby on Rails using rbenv tool.

Contributing to Ruby on Rails Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. API Documentation Guidelines This guide documents the Ruby on Rails API documentation guidelines. Ruby on Rails Guides Guidelines This guide documents the Ruby on Rails guides .

Ruby On Rails James Reynolds. Today Ruby on Rails introduction Run Enviornments MVC A little Ruby Exercises. Installation Mac OS X 10.5 will include Rails Mac OS X 10.4 includes Ruby . What happens if JavaScript is off? No JavaScript That is unacceptable! No JavaScript Change example_controller.rb

HP PHP PHP PHP PHP PHP HiPE Erlang HiPE Erlang HiPE . Perl Perl Perl Perl Perl Perl Ruby Ruby Ruby Ruby Ruby Python 3 Python 3 Python 3 Lua Lua Lua Lua Lua Lua Ruby Matz's Ruby Matz's Ruby benchmarks game 01 Mar 2019 u64q p r o . Python configures and steers fast C/C /Fortran code Passes memory buffers from one library to the next

A Beginner's Guide to Security with Ruby on Rails in BSD Corey Benninger. What's on Tap? Ruby on Rails BSD Security. . Openbsd 3.9 – Install Ruby (pkg_add ruby-1.8.4p1.tgz) . for more install details. Getting the Goods

RUBY ON RAILS - WHAT IS IT? Ruby on Rails (or just Rails) is an open source web application framework. Written in the Ruby programming language. Designed to make programming web applications easier. Abstracts the commonly used and repetitive tasks. HISTORY Created in 2003 by David Heinemeier Hansson. Developed while he was .

API RP 581 is a well-established methodology for conducting RBI in the downstream industry and the 3rd edition of the standard has just been published in April 2016. This paper examines the new features of the 3rd edition particularly for internal and external thinning and corrosion under insulation and it also discusses a case study of application of this latest RBI methodology in France .