diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 6f49f07..0000000 --- a/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -_site/ -_gh-pages/ -CNAME -*.swp -.DS_Store diff --git a/_config.yml b/_config.yml deleted file mode 100644 index e0c20fe..0000000 --- a/_config.yml +++ /dev/null @@ -1,2 +0,0 @@ -name: Learn to Code -highlighter: pygments diff --git a/_includes/exercise.html b/_includes/exercise.html deleted file mode 100644 index 73ba392..0000000 --- a/_includes/exercise.html +++ /dev/null @@ -1,3 +0,0 @@ -
- {{ exercise }} -
\ No newline at end of file diff --git a/_layouts/default.html b/_layouts/default.html deleted file mode 100644 index 47a5ef1..0000000 --- a/_layouts/default.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - {{ page.title }} - - {% capture lvl %}{{ page.url | append:'index.html' | split:'/' | size }}{% endcapture %} -{% capture relative %}{% for i in (3..lvl) %}../{% endfor %}{% endcapture %} - - - - - - - - - - - - - - - - - - - - - - - -
- - {{ content }} - - -
- - - - diff --git a/_layouts/post.html b/_layouts/post.html deleted file mode 100644 index ca87179..0000000 --- a/_layouts/post.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -layout: default ---- -

{{ page.title }}

-

{{ page.date | date_to_string }}

- -
-{{ content }} -
diff --git a/_layouts/session.html b/_layouts/session.html deleted file mode 100644 index 200de95..0000000 --- a/_layouts/session.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -layout: default ---- - - - -
- - -
-{% for task in page.tasks %} - {% if forloop.first %} -
- {% else %} -
- {% endif %} - -

{{ task.title }}

- {{ task.output }} -
-{% endfor %} -
- -
- diff --git a/_layouts/task.html b/_layouts/task.html deleted file mode 100644 index 6304a07..0000000 --- a/_layouts/task.html +++ /dev/null @@ -1,5 +0,0 @@ ---- -layout: none ---- - -{{content}} \ No newline at end of file diff --git a/_plugins/highlight_in_list.rb b/_plugins/highlight_in_list.rb deleted file mode 100644 index cc17105..0000000 --- a/_plugins/highlight_in_list.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Jekyll - module Tags - class HighlightBlock < Liquid::Block - alias_method :old_render, :render - - def render(context) - output = old_render(context) - if @options['inlist'] - output.lines.map {|l| " "*8 + l } - else - output - end - end - end - end -end diff --git a/_plugins/sessions.rb b/_plugins/sessions.rb deleted file mode 100644 index 69bdc7d..0000000 --- a/_plugins/sessions.rb +++ /dev/null @@ -1,109 +0,0 @@ -module Jekyll - - class SessionPage < Page - def initialize(site, base, dir) - @site = site - @base = base - @dir = dir - @name = 'index.html' - - self.process(@name) - self.read_yaml(File.join(base, '_layouts'), 'session.html') - self.data['tasks'] = get_tasks - # load other options - if File.exists?(File.join(base, '_sessions', dir, 'info.yml')) - self.data.merge!(YAML.load_file(File.join(base, '_sessions', dir, 'info.yml'))) - end - - self.data['title'] ||= dir - end - - def get_tasks - Dir.entries(File.join(@base, '_sessions', @dir)).reject{|x| %w{. .. info.yml}.include?(x)}.reject{|x| x[0]=='_'}.sort.map do |n| - t = TaskPage.new(@site, @base, @dir, n) - #t.render - t - end - end - def render(*args) - self.data['tasks'].each {|t| t.data['output'] = t.tap {|t| t.render(*args)}.output } - super - end - - end - - class SessionPageGenerator < Generator - safe true - - def generate(site) - # if we have a session template - if site.layouts.key? 'session' - # put in top level directory - if Dir.exists?('_sessions') - subdirs = Dir.entries('_sessions').reject{|x| %w{. ..}.include?(x)} - subdirs.each do |dir_name| - - site.pages << SessionPage.new(site, site.source, dir_name) - end - end - end - end - end - - # In some ways I want a TaskPage. In others I don't. - # I definitely want something to read in individual task files and render them. - # But in a way more akin to a blog page summary than individual pages - - # Plan: make TaskPages. Don't have a TaskPage generator. Attach TaskPages to relevant SessionPage. - # Render them using TaskPage.content ?? Or does the content get passed in in a different way. - # You don't call post.content ... :( ... Actually it's ok. Content does seem to be passed to liquid. - # When does it get put into the template though? https://github.com/mojombo/jekyll/blob/master/lib/jekyll/site.rb#L225 - # But that just calls page.render: https://github.com/mojombo/jekyll/blob/master/lib/jekyll/page.rb#L105 - # But that just goes here: https://github.com/mojombo/jekyll/blob/master/lib/jekyll/convertible.rb#L90 - # The only bit I don't want is Convertible.write https://github.com/mojombo/jekyll/blob/master/lib/jekyll/convertible.rb#L141 - # Which is called for pages, posts etc. here: https://github.com/mojombo/jekyll/blob/master/lib/jekyll/site.rb#L292 - # So what I really want it to do is allow it to render, but not be placed in the list of pages. - # But then that has to be done manually anyway, so we're fine! - - # This doesn't seem to work. I have problems rendering the TaskPages at the right time. - # Maybe I should merge the TaskPages into the SessionPage's payload - # Actually I didn't have to do this. The above worked. - - class TaskPage < Page - def initialize(site, base, dir, name) - @site = site - @base = base - @dir = dir - @name = name # won't be used - - self.process(@name) # separates into @basename and @ext - self.read_yaml(File.join(base,'_sessions', dir), name) - - self.data['basename'] = @basename - - # self.data['title'] = "#{category_title_prefix}#{category}" # should have title already - end - end - - - - class ExerciseTag < Liquid::Block - # somehow access converter - # really want to do markdown first - - def render(context) - # raise context.inspect - # content = super - # parsed_content = Liquid::Template.parse(content) - # output = context.stack do - # parsed_content.render(context) - # end - # how do I convert this thing??? - "
Task: " + super + "
" - end - end - - -end - -Liquid::Template.register_tag('exercise', Jekyll::ExerciseTag) diff --git a/_sessions/c1prep/0_welcome.md b/_sessions/c1prep/0_welcome.md deleted file mode 100644 index a5c78a5..0000000 --- a/_sessions/c1prep/0_welcome.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Welcome ---- - -Welcome to the course preparation for the Introduction to Web Programming course! - -The course will cover a basic introduction to web progamming, starting from scratch. You will develop your understanding of how the internet works, learn to code a basic site using HTML and CSS, and learn how to manage your code and get your site online using a tool called git. This course is a pre-requisite for all other courses offered by The Oxford Codelab. - -There are many excellent resources on the web for learning a lot of this material. We don't want to reinvent the wheel and will unashamedly point you towards better sources of information when they exist. Rather than teach you everything from scratch, we aim to guide and support your learning. - -### Installing software - -One of the biggest challenges in a course like this is dealing with the different operating systems and hardware that you'll be working on. We have decided against getting everyone to run a linux virtual machine (or similar) for the course, as it's really important that web development is something that you can do in your natural computing environment. - -That does mean that there's a bit of setting up that you will need to do to be ready for the first session next week. Please be patient with this - installing software is fiddly and not always predictable. Most of the work we get you to do won't be like this! - -The tabs on the left hand side will take you through installing the software you'll need for the course. Instructions are given in blue boxes. - -{% exercise %} -The blue boxes tell you what you need to do! -{% endexercise %} - -If you have any problems, please contact the tech team! diff --git a/_sessions/c1prep/1_google_chrome.md b/_sessions/c1prep/1_google_chrome.md deleted file mode 100644 index 4c2fa6f..0000000 --- a/_sessions/c1prep/1_google_chrome.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Google Chrome ---- - -{% exercise %} -Download and install [Google Chrome](https://www.google.com/intl/en/chrome/browser/). -{% endexercise %} - -### Why do I need Chrome? - -Chrome is a free web browser provided by Google. There are several other web browsers that you might have used, including Internet Explorer, Safari, Firefox and Opera. We will be using Chrome as it comes with a good set of developer tools that we will be using over the course. - -[Firefox](http://www.mozilla.org/en-US/) also comes with an excellent set of developer tools (via its [firebug extension](http://getfirebug.com/)). There doesn't seem to be much between Chrome and Firefox+firebug as far as the tools we'll be using go. The decision to recommend Chrome was fairly arbitrary, but means that everyone will be using the same software. diff --git a/_sessions/c1prep/2_sublime_text.md b/_sessions/c1prep/2_sublime_text.md deleted file mode 100644 index 6bace4d..0000000 --- a/_sessions/c1prep/2_sublime_text.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Sublime Text ---- - -{% exercise %} -Download and install the appropriate version of Sublime Text for your computer from [http://www.sublimetext.com/](http://www.sublimetext.com/). -{% endexercise %} - -### Why do I need Sublime Text? - -Sublime Text is a *text editor* - a program that can be used for writing code. - -When you write code it is important that the editor stores just the text you wrote, so that it can be properly interpreted when you run it. Word processors, like MS Word, add a lot of extra information to the text you write - layout, font styles, etc. - so can't be used for this purpose. - -You probably already have a text editor, such as notepad or textedit, on your laptop that could be used for writing code. Sublime Text is better because it also does *syntax highlighting* - it will colour your code, making it easier to see what's going on. - -### Do I need to pay? - -Sublime Text costs $70 but **you can use it for free** as it has an indefinite evaluation period. The duration of the course seems like a pretty reasonable period of time to evaluate the software. If you go on to use it after that you should consider getting a license - it's a good product and the guys who make it have to eat! - -### Why Sublime Text? - -There are many text editors available including many excellent free and/or open source ones. Sublime Text is a popular code editor in the web development world at the moment and benefits from an active community of developers contributing add-ons and improvements. Although it isn't free or open source, we have chosen it as our recommended editor as it: (a) gives a good user experience on mac, linux and windows; (b) is easy to get started with; and (c) can be easily customised when you get more advanced. - -If have a different text editor that you are already used to using, feel free to use that instead! - - - diff --git a/_sessions/c1prep/5_reading.md b/_sessions/c1prep/5_reading.md deleted file mode 100644 index 94688e1..0000000 --- a/_sessions/c1prep/5_reading.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Preparation exercises ---- - -Well done for getting to this point! You should now have all the software you need to start the course. - -In the first session we will be looking at HTML and the overall structure of the internet. We won't be spending much time on these, so it will help if you've at least seen then before. To help everyone has a basic amount of knowledge to start, please do the following: - -{% exercise %} - -1. Watch [these](http://www.youtube.com/watch?v=72snZctFFtA) [two](http://www.youtube.com/watch?v=oN7ripK5uGM) videos about the DNS system: [video1](http://www.youtube.com/watch?v=72snZctFFtA) (excuse the political overtones), [video2](http://www.youtube.com/watch?v=oN7ripK5uGM) -2. Sign up to [General Assembly Dash](https://dash.generalassemb.ly/projects) and complete the whole of Project 1. (Will probably take about 30mins). -3. (Optional) Sign up to [Codecademy](http://www.codecademy.com/). On the [Codecademy web track](http://www.codecademy.com/tracks/web): - 1. Do the project from "1 Introduction to HTML". - 2. Do the project from "2 HTML Structure: Using Lists". - 3. Do the project from "3 HTML Structure: Tables, Divs, and Spans". -{% endexercise %} - -Look forward to seeing you at the first session! diff --git a/_sessions/c1prep/info.yml b/_sessions/c1prep/info.yml deleted file mode 100644 index 6627c7d..0000000 --- a/_sessions/c1prep/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Course Preparation -strapline: Getting you set up and ready to go! \ No newline at end of file diff --git a/_sessions/c1prep_linux/1_git.md b/_sessions/c1prep_linux/1_git.md deleted file mode 100644 index e69de29..0000000 diff --git a/_sessions/c1s1/0_overview.md b/_sessions/c1s1/0_overview.md deleted file mode 100644 index 7159592..0000000 --- a/_sessions/c1s1/0_overview.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Course Overview ---- - -### Who is this course for? - -- You want to start a start-up and be your own technical cofounder -- You want to have your own blog and understand how it works -- You want to have the foundations to teach yourself more - -### What will we learn - -- How to inspect and learn from other sites -- How to put up a webpage -- Basic skills and tools that will be useful for any coding you do - -Hope you will become curious about how the internet works and will look at websites in a different way. - -It's worth pointing out that this is *not* the easiest way to put up a website. There are many site builders/blogging platforms which will allow you to put up a website quickly and easily in a point-and-click manner (eg. [weebly](http://www.weebly.com/) or [wordpress](http://wordpress.com/)). The focus of this course is learning the basics of how and why things work and to provide the basis to build upon in future courses. - -### How to study - -The hardest thing about learning to program is knowing where to start and what to learn. The course aims to provide a basic overview of the technologies used, along with the tools and resources to discover more. We do not aim to cover anything in great depth or comprehensive detail. - -The lectures will be as hands-on and practical as possible. Each week there will be a number of tasks to do in between the sessions to reinforce what you have learnt. It's up to you whether you do the tasks or not, but the more you put in the more you will get out! \ No newline at end of file diff --git a/_sessions/c1s1/1_what_is_a_webpage.md b/_sessions/c1s1/1_what_is_a_webpage.md deleted file mode 100644 index 80c41dd..0000000 --- a/_sessions/c1s1/1_what_is_a_webpage.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: What is a web page? ---- - -A webpage is just a set of files that your web browser knows how to display. - -There are three possibilities for the types of files they could be: HTML, CSS and Javascript. Most web pages will be a mixture of all three. Because the files have to be able to be interpreted by all web browsers on all operating systems, the choices are limited and don't change very often. - - - -HTML, CSS and Javascript are known as **client-side** technologies, because they are sent to your web browser (the client). - -#### Programming language vs markup language - -HTML (*HyperText Markup Language*) is a way of writing information so that it can be interpreted by a web browser. It is *not* a programming language - you can't do calculations in it - it is a _markup_ language. CSS is also a markup language. Javascript is a programming language. - -#### Content/style separation - -Back in the early days of the web HTML would both store the information and tell the browser how to display it. People then realised that this was a bad idea - making a small change such as changing the colour of a heading would require edits all over the place, which made sites hard to maintain. HTML is now used just to display the information (text etc.) that is stored in the page. CSS is used to tell the browser how to display the information. - -#### Viewing HTML, CSS and js - -Because the HTML, CSS and js are sent to your browser, it is easy for you to look at them. **There are no secrets in HTML, CSS or js.** If there's a part of a webpage that you like, it's easy to find out how it is coded and use the technique yourself. - -Every browser provides a way to look at the source of the page you're currently viewing. In Chrome you do `View > Developer > View Source`. This will show you the raw HTML but isn't always the easiest thing to look at. - -Several browsers also provide developer tools, which allow you to *interactively* view the page source. In Chrome you can access these by doing `View > Developer > Developer Tools`. If you use Firefox, you can get similar functionality with the Firebug plugin. These tools are the best way to investigate a web page. Over the course you will be using them a lot on your own pages, especially when things aren't working exactly as you expect. - -There are a few features of the Chrome developer tools that it is worth pointing out now. - - -{% exercise %} -1. Open this page in Google Chrome -2. View the page source by doing one of the following: - * View > Developer > View Source - * Tools > View Source -3. Open the developer tools by doing one of the following: - * View > Developer > Developer Tools - * Tools > Developer Tools -4. Use the magnifying glass in the bottom left to hover over bits of the page and find the related HTML. -5. Hover over the HTML code in the developer tools box and watch as different parts of the page are highlighted. -6. Try changing some of the CSS on the right hand side. To undo any changes just refresh the page. -7. Have a look on the `Resources` tab. See if you can find the CSS, javascript and image files used on this page. -8. Visit a few of your favourite websites and repeat this process. -{% endexercise %} diff --git a/_sessions/c1s1/2_servers.md b/_sessions/c1s1/2_servers.md deleted file mode 100644 index 364cefc..0000000 --- a/_sessions/c1s1/2_servers.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Web servers ---- - -You can think of the internet as a massive network of computers that can send files to one another. The computers that hold web pages are called _servers_. **Servers are large, specialised computers that are permanently connected to the internet.** - -Once the address of the web server has been found your request is forwarded on to it, the web server will interpret your request and send back one or more files. We now look at the technology involved in this process. - -### Static vs dynamic sites - -There are two main possibilities server-side: either your site is static or dynamic. - -* In a static site all the pages are pre-prepared and the web server just sends them to the browser. -* In a dynamic site the pages are prepared on-the-fly pulling information out of a database depending on what the user asked for. - -Most of the sites you can think of will be dynamic sites (e.g. [facebook.com], [reddit.com], [amazon.com], ..). - -### Server-side technologies - -There are many options for building a dynamic server-side site - you're pretty much free to do what you like. Some common choices are: - - - diff --git a/_sessions/c1s1/3_urls_and_dns.md b/_sessions/c1s1/3_urls_and_dns.md deleted file mode 100644 index 818eec6..0000000 --- a/_sessions/c1s1/3_urls_and_dns.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Introducing the URL ---- - -Many of our web interactions begin with a URL (*uniform resource locator*) being typed into our web browser address bar. Let's look at an example: `http://www.bbc.co.uk/news/`. - -This URL has several different parts to it: -- `http` : the _protocol_ or *how* to fetch the information -- `www.bbc.co.uk` : the _host_ or *where* to fetch it from -- `/news` : the _path_ or precisely *what* information to fetch - -When we type the URL into the address bar a request is sent over the internet and some information is returned to us. - -The protocol describes how the information is transmitted. Other possibilities include `https` for secured communication, `ftp` for file transfer and `git` which you'll learn about later. - -The host describes where the information should come from and the path tells that location precisely what information to send. - -In general a URL can be more complicated than this. URLs can also contain _query parameters_, _fragments_ and _port information_. We will leave these for now but will point them out when we meet them later. Instead we will focus on exactly what information is being sent and who is sending it. - -Each computer on the internet has an address (an _IP address_) so that requests can be sent to it and files returned - much like a telephone number. The backbone of the internet is a network of _routers_ that are responsible for routing files from one IP address to another. - -### DNS - -IP addresses are a sequence of numbers and '.'s such as `212.58.244.67`. These aren't very easy to remember. Instead the internet works on a domain name system, that matches domain names such as `bbc.co.uk` to IP addresses. - -{% exercise %} -Type `212.58.244.67` into your browser's address bar. What happens? -{% endexercise %} - -One of the first things that happens when you type a URL into your browser is a _DNS lookup_: your computer contacts a DNS server (*Domain Name System server*), which is basically a massive address book of IP addresses. The DNS server converts the domain name from the URL (e.g. `bbc.co.uk`) into an address for a server (such as `212.57.244.67`). - -### Putting up a website - -If you want to put up your own website at your own domain name you need two things: - -1. A web server to serve your site -2. A domain name to point towards it - -There are many options for web servers - you don't have to physically have your own one. There are many companies that will offer web hosting, often providing you with space on a shared server. Later in the course we will use the free hosting offered by GitHub through GitHub Pages. - -To buy a domain name you need to use a domain registrar. Examples include [123-reg.co.uk](http://www.123-reg.co.uk/), [godaddy.com](http://www.godaddy.com/) and [namecheap.com](http://www.namecheap.com/). You pay the registrar to contact the body who manages a TLD (e.g. .com, .org., .co.uk) and put your server's IP address in their DNS address book. If someone else already owns the domain you might be able to buy it off them, but this can be expensive! - -Many domain registrars will try to sell you hosting and other site building tools when you buy a domain. It's important to remember that the domain name is completely separate from the hosting and you don't need to do them both through the same company - don't buy anything you're not going to use. - diff --git a/_sessions/c1s1/4_first_page.md b/_sessions/c1s1/4_first_page.md deleted file mode 100644 index 2af64e5..0000000 --- a/_sessions/c1s1/4_first_page.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Creating an HTML page ---- - -One of the nice things about HTML is you don't need any fancy software to test it out on your laptop: all you need is a text editor and a web browser. - -{% exercise %} -1. Inside your `coding_course` folder create another folder called `first_site`. -2. Open Sublime Text. -3. Write "Hello" -4. Save the file as `index.html` in the `first_site` folder -5. Open `index.html` in Chrome. Depending on your version of Chrome - * File > Open ... - * Cmd-o (Mac) or Ctrl-o (Windows) - -{% endexercise %} - -### Why index.html? - -In the old days of the web, navigating a website was a lot more like moving around the folder system on your laptop. You would go to a base site and there would just be a list of the files and folders available: an index. Because of this `index.html` is still the default file that a server will serve when you navigate to a folder in the web browser. - -{% exercise %} -1. Go back to 'index.html' in Sublime Text. -2. Change the text to -{% highlight html %} -

Hello

-{% endhighlight %} -3. Go back to 'index.html' in Chrome and refresh the page (Cmd-R) -{% endexercise %} - -This is your first line of HTML. It has an open tag and a close tag. They tell your browser to display the text in-between as a heading. diff --git a/_sessions/c1s1/5_more_html.md b/_sessions/c1s1/5_more_html.md deleted file mode 100644 index 4e7325c..0000000 --- a/_sessions/c1s1/5_more_html.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: More HTML ---- -Now we will look at some slightly more interesting things you can do with HTML. - -### HTML file layout - -{% highlight html %} - - - - Page title - - - ... - - -{% endhighlight %} - -* The doctype tells you what sort of html you're using (html5, html4 ...). With html5 it's simple - you just write `html`. -* Everything is wrapped in an ` ... ` tag -* Things within the ` .. ` are used to provide information about the page -* Only things within the ` ... ` tags are displayed on the page -* ... for example the text within ` ... ` will be displayed in the browser bar - -### Headings - -{% highlight html %} -

Top level heading

- -

Lower level heading

-{% endhighlight %} - -* There are six levels of heading `h1` ... `h6` -* The higher numbers are more important -* It's usual to only have one `h1` on a page -* You rarely see anything below `h4` in real pages - -### Paragraphs and text - -{% highlight html %} -

This is a paragraph.

- -

This is another paragraph. It has some italic text and some bold text.

-{% endhighlight %} - -* Paragraphs are created using the `

` tag -* The `` tag is used to provide emphasis. In reality that means italics - in fact the tag `` also works. Using em is better though as it fits with the idea of *semantic markup* - marking your information as to its meaning, instead of how you want it to look. -* The `` tag is used to make text stand out. It basically means bold - `` also works, but `` is better - see above. - -### Comments - -{% highlight html %} - -{% endhighlight %} - -* Comments will not display in the page ... -* ... but they will display in the page source. Don't be rude! - -### Lists - -{% highlight html %} -

-{% endhighlight %} - -* Lists have a nested structure -* `
    ` is for an *unordered* list. This means bullet points. -* `
      ` is for an *ordered* list. That means automatic numbering. -* In both types of list you add items using a `
    1. ` tag. This stands for *list item*. - -### Links - -{% highlight html %} -this is a link to facebook -{% endhighlight %} - -* The `href` property tells you where the link will point -* You can specify this link in different ways: - * absolute external link e.g. "http://www.facebook.com" - * absolute local link e.g. "/about". This links to a file relative to the root of your webserver. For example if your site is at `www.example.com` the link will point to `www.example.com/about` - * relative local link e.g. "about". This links to a file relative to the current html document. In this case it will link to the file called `about` in the same folder as your current html file. -* You can also link to places in the same document using `href="#my_tag"`. More on this later. -* You can get the link to open in a new tab like this: `` - -### Images - -{% highlight html %} -my cat -{% endhighlight %} - -* The `alt` tag is for providing a description of your image. This is useful for partially sighted people using screen readers, or in case the image doesn't load. -* The file can be linked to in the same way as href. In the example above we use a relative local link to a file called `my_cat.png` in the same folder as the html file. - -### Tables - -{% highlight html %} - - - - - - - - - - - - - - - - - - - - - -
      Column1 HeadingColumn2 Heading
      Row1, Column1Row1, Column2
      Row2, Column1Row2, Column2
      Row3, Column1Row3, Column2
      - -{% endhighlight %} - -Now you will use these ideas to create a richer web page. - -{% exercise %} -1. Create a folder called `coding_course` to hold all your work for the course. -1. Go to the github repository for this session: [https://github.com/code61/learning_html](https://github.com/code61/learning_html) -2. Download the code into your `coding_course` folder (by clicking 'Download ZIP' in the bottom right). -3. Open the whole folder in Sublime Text -4. Open the file `example.html` in Chrome and look around with the developer tools -5. Open the file `notes.html` in Sublime Text. -6. Change `notes.html` into valid html so that it looks like `notes_solution.jpg` -{% endexercise %} diff --git a/_sessions/c1s1/6_homework.md b/_sessions/c1s1/6_homework.md deleted file mode 100644 index 941e939..0000000 --- a/_sessions/c1s1/6_homework.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Homework ---- - -### Finishing off - -{% exercise %} -Finish the HTML exercise from the last section. -{% endexercise %} - -### Preparation for next time - -{% exercise %} -1. Complete the whole of Project 2 on the [General Assembly Dash](https://dash.generalassemb.ly/projects) site. -3. (Optional) Do the projects from the [Codecademy Web Track](http://www.codecademy.com/tracks/web) Sections 4, 5 & 6. -{% endexercise %} - -### Make a start on your own site - -{% exercise %} -Use what you've learnt from the HTML exercise and the Dash projects to improve your `first_site/index.html`. Maybe add some content about yourself. Don't worry if it doesn't look great yet - we'll be working on it more in the next few weeks. Just make sure it says something more than 'Hello'! -{% endexercise %} - diff --git a/_sessions/c1s1/info.yml b/_sessions/c1s1/info.yml deleted file mode 100644 index 9337d1a..0000000 --- a/_sessions/c1s1/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 1 -strapline: Getting going \ No newline at end of file diff --git a/_sessions/c1s2/1_recap.md b/_sessions/c1s2/1_recap.md deleted file mode 100644 index 82f6f1d..0000000 --- a/_sessions/c1s2/1_recap.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: "Recap from last time" ---- - -### HTML/CSS - -* Webpage is just a collection of files: HTML, CSS & Javascript. -* We can edit these files locally. -* We can create them locally (using a text editor) and view then in a -browser. - -### Putting your site online - -We're going to use [BitBalloon](https://www.bitballoon.com/) to host our site - BitBalloon will provide the server where the files for our site is stored. - -{% exercise %} -1. Create an account on [BitBalloon](https://www.bitballoon.com/). -2. Upload your site by dragging and dropping your `first_site` folder onto the BitBalloon website. -3. Visit your site online! -{% endexercise %} - -Your site will currently show up with a url something like [teller-balances-48402.bitballoon.com](teller-balances-48402.bitballoon.com). Part of your homework will be to buy your own domain name to point towards BitBalloon. (You will need to upgrade to the $5/month BitBalloon account to make this possible.) - -### Preparation - -{% exercise %} -1. Go to the github repository for this session: [https://github.com/code61/html2](https://github.com/code61/html2) -2. Download the code into your `coding_course` folder (by clicking 'Download ZIP' in the bottom right). -{% endexercise %} - diff --git a/_sessions/c1s2/2_css.md b/_sessions/c1s2/2_css.md deleted file mode 100644 index 85a05ae..0000000 --- a/_sessions/c1s2/2_css.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: CSS ---- - -Last time we looked at HTML, and saw how this was used to mark up the information in a webpage. Right now, your HTML pages don't look very good, as you haven't given any styling information. The way to do this is using CSS (Cascading Style Sheets). - -CSS is a way of separating the way your page looks from the content that it displays. As an extreme example of this check out [CSS Zen Garden](http://www.csszengarden.com/) - by clicking on the links you completely change how the site looks, but the html remains unchanged. - -There are a few ways to include CSS in an HTML file: - -1. Put the css inline in the html. -2. Put the css in a `` section in the `` -3. Link to a separate `.css` file in the `` - -The first way is sometimes useful, but defeats the point of using CSS to separate presentation and information. The second way is a bit better and is what we'll do now - it's nice to have everything in a single file when you're just starting. The third way is the best. We'll look at how to do this next time. - -### CSS in the `` - -If you're putting your CSS in the `` of your html file (option 2) it should look something like this: - -{% highlight html %} - - Some title - - -{% endhighlight %} - -The bit inside the ` - - - - - -{% endhighlight %} - -We did this to make your first experiments with CSS quick an easy. In a live site it is considered bad practice to put your CSS inside the `head` section: Typically a site will have one set of styles that apply to all the pages. By separating these CSS rules into their own file you (a) reduce repetition in your code and (b) reduce the amount of information that has to be sent to the browser for each page - if the CSS file applies to the whole site, it only needs to be sent to the visitor once. - -To link to an external CSS file you can do the following: -{% highlight html %} - - - - My page - - - - - - -{% endhighlight %} - -### Linking to other files - -Linking to other files (stylesheets, javascript files, images) can be done in several ways, just like linking to another page. Say you have the following directory structure: - - first_site - | - ---- index.html - | - ---- images - | | - | ---- background.jgp - | - ---- stylesheets - | - ---- main.css - -and you're going to deploy your site to "http://www.my_first_site.com". Suppose you want to link to `main.css` from `index.html` and to `background.jpg` from `main.css`. There are three different styles of links you can use: - -#### 1. Absolute links - -Absolute external links include the complete url to the resource you're linking to. **Absolute links start with either http:// or https://**. - -{% highlight html %} - - -{% endhighlight %} -{% highlight css %} -/* in main.css */ -body { - background-image: url("http://www.my_first_site.com/images/background.jpg"); -} -{% endhighlight %} - -Absolute external links can be used to link to resources held on different sites, but wouldn't usually be used for links within your own site. They're a bit fragile - if you change your domain name all the links will break. They also won't work when you're developing locally. - -#### 2. Root-relative links - -Root-relative links contain the path to the resource *relative to the site's root*. The site's root is (roughly) the folder that contains the site - in this case, `first_site`. **Root-relative links begin with a `/`**: - -{% highlight html %} - - -{% endhighlight %} -{% highlight css %} -/* in main.css */ -body { - background-image: url("/images/background.jpg"); -} -{% endhighlight %} - -Root-relative links are a bit more flexible than absolute external links: e.g. if you change your domain name everything will still be fine. They're sometimes useful for your own static sites, but probably won't work when developing locally (because the root will be taken to be the root of your file system and not the folder containing the site!). - -#### 3. Document-relative links - -Document-relative links contain the path to the resource *relative to the file where the link is written*. **Document-relative links don't begin with `/`**: - -{% highlight html %} - - -{% endhighlight %} -{% highlight css %} -/* in main.css */ -body { - background-image: url("../images/background.jpg"); -} -{% endhighlight %} - -To link to the stylesheet from `index.html` we use `stylesheets/main.css` which says "look in the same folder I'm in (`first_site`) and find a folder called `styleheets` and a file in it called `main.css`". - -To link to the image from the stylesheet is slightly more complicated: we use `../images/background.jpg`. This means "go to the folder above the one I'm in (I'm in `stylesheets`, so that's `first_site`) and find a folder called `images` and a file in it called `background.jpg`". - -
      -
      -

      Important to know

      -
      -
      - In document-relative links (and in many other places e.g. command line navigation) -
        -
      • . means in the folder that I'm in
      • -
      • .. means in the folder above the one that I'm in
      • -
      -
      -
      - -Relative links are the most flexible - they will work on your local file system. The only think you have to be careful about is moving your files into different folders, which can cause links to break. - -**You should be using relative local links in these exercises.** - -For a recap of all this, read [this article](https://www.inkling.com/read/dreamweaver-cs6-missing-manual-david-sawyer-mcfarland-1st/chapter-4/understanding-links). - -{% exercise %} -1. Return to `exercise1.html` and separate the CSS out into a separate file (called `exercise1.css`). -2. Check that the CSS still shows up when you view the site in the browser. -3. Make a change in `exercise1.css` and check that you can see that in the browser. (You might need to refresh the page a few times). -{% endexercise %} diff --git a/_sessions/c1s2/6_homework.md b/_sessions/c1s2/6_homework.md deleted file mode 100644 index f4ecc4a..0000000 --- a/_sessions/c1s2/6_homework.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Homework ---- - -### Finishing off - -{% exercise %} -Finish off both CSS exercises from class. Check your solutions online: -
        -
      • Find the HTML2 repository on Code61's github page.
      • -
      • In the `branch` dropdown (just above the list of files) select the `solution` branch.
      • -
      • Click on the files below to see the solution
      • -
      -{% endexercise %} - -### Review - -{% exercise %} -Watch [this video](http://generalassembly.wistia.com/medias/qzig8mp4mv) from General Assembly, which recaps developing locally and deploying to BitBalloon. -{% endexercise %} - - -### Buy a domain name - -Your domain name will be used to point towards your personal website for the course - it's up to you exactly what this will be about. You might want to use this opportunity to create a basic 'personal landing page' saying a bit about yourself and where to find more information. Or you might want to put up a blog. Alternatively if you want you can put up a page about something you are interested in (or [your dog](http://jamfly.info/)). You will need to pick a domain name accordingly! - -To buy a domain name you need to visit a domain registrar. Examples are: - -* [123-reg](http://www.123-reg.co.uk/) -* [Godaddy](http://www.godaddy.com/) -* [Namecheap](http://www.namecheap.com/) -* [dot.tk](http://www.dot.tk/en/index.html?lang=en) (.tk domains are completely free!) - -There probably won't be a huge difference in price between these sites. You might be able to find a special offer on one of them if you shop around a bit though. Ultimately the domain you choose isn't that important for the course - the whole point is to practice pointing a domain name towards a server. - -{% exercise %} -1. Buy your own domain name. -2. Follow [these instructions](https://www.bitballoon.com/docs/custom_domains/) to point your custom domain towards your code on BitBalloon. -{% endexercise %} - - -### More HTML/CSS - -{% exercise %} -
        -
      1. Complete the whole of Project 3 on the [General Assembly Dash](https://dash.generalassemb.ly/projects) site.
      2. -
      3. Make some changes to your `first_site` based on what you've learnt. Update the online version of your site, by re-uploading to BitBucket.
      4. -
      5. (Optional) Do the projects from the [Codecademy Web Track](http://www.codecademy.com/tracks/web) Sections 7, 8 & 9.
      6. -
      7. (Optional) Read [this article](https://www.inkling.com/read/dreamweaver-cs6-missing-manual-david-sawyer-mcfarland-1st/chapter-4/understanding-links) about absolute vs. relative links.
      8. -
      -{% endexercise %} - - diff --git a/_sessions/c1s2/_1_using_git.md b/_sessions/c1s2/_1_using_git.md deleted file mode 100644 index 9980b8c..0000000 --- a/_sessions/c1s2/_1_using_git.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: "Intro to Git" ---- - -Git is a version control system. It allows you to keep the entire history of your code, and makes it easy to share and collaborate with others. - -To use git you need to create a **Git repository**. You can think of a git repository like this: - -![Basic git](/assets/basic_git.png) - -- A repository contains lots of **commits**. Each commit is essentially a different version of your files. -- Commits can be organised into **branches**. A repository can contain many different branches. Branches are often used to develop new application features - that way the main codebase still works while the feature is being developed, and the new code can be *merged* in when it's working. -- Branches have names, so you can keep track of them. When you first set up a repository, you'll just have one branch and it will have the default name - **master**. - -### What does a git repository look like? - -On your laptop, a git repository is just a **special type of folder**. Any folder can be made into a git repository (but not all folders should - e.g. don't make your entire documents directory into a git repository, you'll run into problems). You'll normally make a new git repository for each coding project you work on. - -If you look inside the folder, you won't see all the different versions stored there (they are actually there - just stored inside a hidden folder called `.git`) - you'll only see the files that are in your **working copy**. Normally this working copy will contain the files from the last commit on the master branch, along with any changes you've made. - -### Making a commit - -To save some changes into the repository you need to create a commit. When you create a commit you get to write a message, to help remind yourself (and others) what changes you made (and why you made them). Once you've created a commit, you'll be able to come back to this version of your code at any point in the future. - -Adding files to a git repository is actually a two-stage process: first you have to **add** them to something called the **index** and then you have to **commit** them. This is useful when you get more advanced, but we'll usually do those things together for the time being. - -![Index and working tree](/assets/index_working_tree.png) - -{% exercise %} -1. Set up your `first_site` folder as a git repository. -2. **Add** your work to the index. -3. **Commit** your work to the repository, with a message e.g. "Initial import" -4. Make some change to index.html (in Sublime Text) -5. **Add** your changes to the index. -6. **Commit** them to the repository. -{% endexercise %} - - -### Git with SourceTree - -#### Creating a git repository - -1. Open SourceTree -2. Select File > New / Clone -3. Select the 'New' option -4. Navigate to the folder you want to make into a git repository. - -#### Adding to the index - -1. Select all the files in the working tree section. -2. Click the "Add" button at the top. -3. You should see the files move to the 'Index' section - -#### Committing to the repository - -1. Once you have files in your 'Index' section, click on 'Commit'. -2. Write a commit message explain what you've done (and maybe why). -3. Click "Commit" - -### Git with the command line - -#### Creating a git repository - -1. Using the command line, navigate to the folder you want to make into a repository. -2. **Inside the target folder** run the command - - git init - -3. To check this worked run the command - - git status - -#### Adding to the index - -1. Inside the folder, run the command - - git add --all - -3. To check this worked run the command - - git status - -#### Committing to the repository - -1. Inside the folder, run the command - - git commit -m "write your message here" - -3. To check this worked run the command - - git status - - \ No newline at end of file diff --git a/_sessions/c1s2/_2_pushing_to_github.md b/_sessions/c1s2/_2_pushing_to_github.md deleted file mode 100644 index 5594d0a..0000000 --- a/_sessions/c1s2/_2_pushing_to_github.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Pushing code to Github ---- - -Github is a site which will host a git repo online for you, making it easy to collaborate with others. We'll now see how to put some code online. - -### Aside: serving a site via Github Pages - -Normally when we push code up to github, it just sits there for others to see and contribute to. The code we're about to push up happens to be the code for a website. Instead of the files just sitting there, we want github to *serve* them as a website. The way github does this is through its [github pages](http://pages.github.com/). - -There are several ways of getting GitHub to publish your site as a GitHub page. We're going to use a simple trick: in the branches panel of the GitHub app, change the name of the current branch from `master` to `gh-pages`. - -
      If you haven't verified your email with github (you'll see a warning at the top of the screen when you log in). Your GitHub won't serve your page at all. Make sure you've verified you email address, before continuing!
      - -### Pushing code up to github - -Go to github, login, and click "Create New Repo" in the top left hand corner. - -![Creating a repo on GitHub](/assets/create_repo.png) - -Follow the instructions, calling it something like `first_site`. **Do not** click the box which says 'Create a readme with this repository'. You'll get to a page when it'll describe how to get your code online. You want to follow the instructions for "Pushing an existing repository to github". - - -{% exercise %} -1. Log in to GitHub and check you've verified your email address. -2. Change the name of your master branch to 'gh-pages'. -3. On github create a new repository called 'first_site'. -4. Push your code up to github. -3. On Github check you can see your `first_site` code. -4. On the code page on github, click on Settings. It should tell you (about half way down) the url where they've published your site. Have a look to see whether you can see it! -5. (If you finish early) Make a change to `index.html` in Sublime Text. Add and commit the change to the repository and then push it to GitHub. Make sure you can see the change in the code on GitHub and also in the published page. -{% endexercise %} - -### Git with source tree - -#### Change the branch name to 'gh-pages' - -1. Go to the branches section on the right hand side. -2. Right-click on the name and select 'rename'. - -#### Pushing to github for the first time - -1. In the 'Repository' menu, click 'Add remote'. -2. Copy the git url (from the bottom right) on github, and copy it into the source tree 'URL/path' box. - -#### Pushing for a second time - -### Git with the command line - -#### Change the branch name to 'gh-pages' - -1. Using the command line, navigate to the repository folder. -2. Run the command: - - git branch -m gh-pages - -3. To check this worked, run the command: - - git branch -a - -#### Pushing to github for the first time - -We're assiming here that you've just created your repository and are on the github new repository screen. - -![Push repo to GitHub](/assets/push_repo_github.png) - -If you've set up ssh keys, go for the ssh option, if not, go for https. You should end up doing something like: - - $ git remote add origin git@github.com/yourusername/first_site.git - $ git push -u origin master - -You might now be prompted to add your github username and password (if you're doing the https method). If all goes well, when you go to github you should see the `first_site` folder containing your html file. - -#### Pushing to github for a second time - -1. In the repository folder, run the command - - git push \ No newline at end of file diff --git a/_sessions/c1s2/info.yml b/_sessions/c1s2/info.yml deleted file mode 100644 index 7948f0d..0000000 --- a/_sessions/c1s2/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 1 -strapline: Git and CSS \ No newline at end of file diff --git a/_sessions/c1s3/1_why_is_css_hard.md b/_sessions/c1s3/1_why_is_css_hard.md deleted file mode 100644 index eafcf56..0000000 --- a/_sessions/c1s3/1_why_is_css_hard.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: What's hard about CSS? ---- - -You've seen quite a bit of CSS now; it all seems quite straightforward - you write some css, tweak it 'til it looks good and you're done! In theory this is exactly how CSS works and is why CSS is brilliant. - -
      - -
      - -Unfortunately, the realities are not quite so straightforward. Different browsers will render CSS with subtle differences. Take a look at the cat picture above. The styling is relatively simple - all we've done is add a border and a shadow. The following CSS will probably do this in your browser: - -{% highlight css %} -.img-polaroid { - padding: 4px; - border: 1px solid rgba(0, 0, 0, 0.2); /* transparent black border */ - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -} -{% endhighlight %} - -However, to get this effect in all browsers you need the following: - -{% highlight css %} -.img-polaroid { - padding: 4px; - background-color: #fff; - border: 1px solid #ccc; /* grey border for browsers that can't do transparency */ - border: 1px solid rgba(0, 0, 0, 0.2); /* put the transparency after for browsers that do */ - -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* some browers only understand webkit box shadow */ - -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* others need this */ - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -} -{% endhighlight %} - - **Just because your site looks good in Chrome, doesn't mean it will look good in Internet Explorer.** Making your site look good (or even presentable) in multiple browsers takes time, effort and experience. - -### What else is hard about CSS? - -About 5 years ago, 'all' you would have had to worry about is the cross-browser display issues. Since then, the mobile web has exploded and you have another (far more important) concern: how will your site look when viewed on a mobile? - -Making webpages that look good when viewed at multiple different sizes is a whole new level of complexity. - -### Should I just give up then? - -You might be the sort of person who relishes this sort of challenge - if so, great! If not, help is at hand ... - diff --git a/_sessions/c1s3/2_twitter_bootstrap.md b/_sessions/c1s3/2_twitter_bootstrap.md deleted file mode 100644 index 7ad5844..0000000 --- a/_sessions/c1s3/2_twitter_bootstrap.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Twitter Bootstrap ---- - -[Twitter Bootstrap](http://getbootstrap.com) is set of CSS (& Javascript) files, released by the makers of Twitter. - -Twitter Bootstrap is a set of **ready-made CSS files** that provide solutions to **common presentation requirements** in a **cross-browser and responsive** way. To make use of Twitter Bootstrap, you need to do two things: - -1. Link to the Twitter Bootstrap stylesheet in the `head` of your html page. -2. Attach the relevant Twitter Bootstrap class to you html element. - -### An example: making a stripy table - -Suppose you want a Zebra-esque table like this fine specimen: - - - - - - - - - - - - - - - - - - - - - - - - - -
      I am aZebra table!
      Look at mystripes.
      Do you find thembeautiful?
      Do you find themmesmerising?
      Wooaahh .... such stripiness!
      - -You have a look at the [Twitter Bootstrap table documentation](http://getbootstrap.com/css/#tables) and discover that you need to add the `table table-striped` class to the `` tag: - -{% highlight html %} -
      - ... -
      -{% endhighlight %} - -This will apply the relevant CSS rules from the bootstrap CSS file. If you're interested, you can go into Developer Tools and view the rules that apply e.g. - -{% highlight css %} -/* from line 1950 of bootstrap.css */ - -.table-striped tbody tr:nth-child(odd) td, -.table-striped tbody tr:nth-child(odd) th { - background-color: #f9f9f9; -} -{% endhighlight %} - -### Responsive design - -**Responsive design** means designing your sites so that they look good on all screen sizes. - -Twitter Bootstrap promotes a 'mobile first' philosophy, encouraging you to design your site so that it looks good at all sizes from the very beginning. It provides a lot of useful CSS that helps you to do this. - -We're not really going to cover responsive design in depth in class, but the Bootstrap docs do a good job of explaining what's possible. Take a look at the [grid system](http://getbootstrap.com/css/#grid) as an example. - -{% exercise %} -The aim of the rest of this session will be to create the website for ["Sam's Sarnies"](http://code61.github.io/bootstrap_exercise/) using Twitter Bootstrap. - -
        -
      1. -Go to the github repository for the [bootstrap exercise](https://github.com/code61/bootstrap_exercise.git). Download the code into your `coding_course` folder (by clicking 'Download ZIP' in the bottom right). -
      2. -
      3. -Open `bootstrap_exercise/index.html` in your browser. -
      4. -
      5. -Go to the [Bootstrap](http://getbootstrap.com) website (it's hosted at github, like your `first_site`) and click the `Download Bootstrap` button (not the Download Source). -
      6. -
      7. -Unzip and copy the `dist` folder into the `bootstrap_exercise` folder. -
      8. -
      9. -Open `index.html` in Sublime Text and Chrome. -
      10. -
      11. -Add a link to the twitter bootstrap stylesheet into `index.html` - -{% highlight html %} - -{% endhighlight %} -Note that you're using a document-relative link to a file two subfolders down. - -
      12. -
      13. -Refresh the page in Chrome. Notice how the fonts have changed. -
      14. -
      15. -Add the following line to the `head` section: - -{%highlight html %} - -{% endhighlight %} -as suggested in the `CSS / Overview` section of the [Bootstrap docs](http://getbootstrap.com/css/#overview-mobile). -
      16. -
      -{% endexercise %} diff --git a/_sessions/c1s3/3_bootstrap_layout.md b/_sessions/c1s3/3_bootstrap_layout.md deleted file mode 100644 index 43fdd00..0000000 --- a/_sessions/c1s3/3_bootstrap_layout.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Bootstrap layout ---- - -Bootstrap gives you several options on how to layout your page. To find out more take a look at the [Grid system docs](http://getbootstrap.com/css/#grid) on the Bootstrap site. Some of these options will work out-of-the-box with *responsive design* - so that you can create a single html page which will look good whether viewed on a laptop, tablet or phone. - -We'll just look at a few of the most important layout options here: - -### Page margins - -Bootstrap makes it easy to center content on your page and provide sensible page margins. To do this make use of the `container` class: - -{% highlight html %} - -
      - - - -
      - -{% endhighlight %} - -### Columns - -Bootstrap works on a grid layout, with 12 columns (by default). You can create a column layout with the `row` and `span` classes: - -{% highlight html %} -
      -
      - -
      -
      - -
      -
      - -
      -
      -{% endhighlight %} - -The number after the `col-sm-` determines how many of the 12 grid columns that page column takes up. The `sm` bit determines the width at which the columns will collapse on top of each other (which is useful when viewing your site on a phone). For more information see the [Grid system docs](http://getbootstrap.com/css/#grid). - -{% exercise %} -
        -
      • Add a div class='container' around the page content.
      • -
      • Create a row at the top of the page, with two columns, with the left twice as wide as the right. Put the h1 in the left column and the img src='images/sandwich.png' on the right.
      • -
      • Create a row with three equal colums to hold each of 'The Buzz' divs.
      • -
      -{% endexercise %} diff --git a/_sessions/c1s3/4_more_bootstrap.md b/_sessions/c1s3/4_more_bootstrap.md deleted file mode 100644 index d1540c2..0000000 --- a/_sessions/c1s3/4_more_bootstrap.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: More Bootstrap ---- - -### Typography - -Skim through the [typography section](http://getbootstrap.com/css/#type) of the bootstrap docs. - -{% exercise %} -1. Change the quotes in 'The Buzz' to use [blockquotes](http://getbootstrap.com/css/#type-blockquotes). (Don't worry about the vertical grey lines - we'll remove those later.) -2. Change the paragraphs in 'Our mission' to be [lead body copy](http://getbootstrap.com/css/#type-body-copy). -{% endexercise %} - - -### Badges and Buttons - -Check out the [buttons section](http://getbootstrap.com/css/#buttons) (CSS > Buttons). - -{% exercise %} -1. Change the 'Send' button to a success button: -{% highlight html %} - -{% endhighlight %} -You might also need `btn-small` in the Recent Activity section. -2. Make the social links at the bottom in to large buttons (we'll colour them later): -{% highlight html %} - -{% endhighlight %} -{% endexercise %} - -### Images - -Have a look at the [image section](http://getbootstrap.com/css/#images) of the Bootstrap docs (CSS > Images). - -{% exercise %} -1. Make the images in 'The Buzz' round, by adding the `img-circle` class. -2. You can center the image by adding the [alignment class](http://getbootstrap.com/css/#type-alignment) `text-center`. -2. Change the main sandwich image into a `img-responsive`, as described in the [responsive images section](http://getbootstrap.com/css/#overview-responsive-images). Try resizing your browser and see how it changes size. -{% endexercise %} diff --git a/_sessions/c1s3/5_modifying_bootstrap.md b/_sessions/c1s3/5_modifying_bootstrap.md deleted file mode 100644 index 5f19757..0000000 --- a/_sessions/c1s3/5_modifying_bootstrap.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Modifying Bootstrap ---- - -
      -Warning: Bootstrap has been designed and heavily tested for good cross-browser compatibility. Unless you know what you're doing or have a lot of time, it's probably best to stick with their layout and tweak small things e.g. fonts and colours. Just because it looks great in your browser doesn't mean it will look great in everyone's! -
      - -If you're going to modify Bootstrap **don't touch the Bootstrap files**. Instead create a new css file of your own to overwrite anything you don't want. This means when a new version of Bootstrap comes out you can upgrade by dragging the new version over the top of the old, without losing any modifications. - - -{% exercise %} -1. Create a file called `main.css` and write the following CSS: -{% highlight css %} -#social-buttons button { - color: white; -} -.btn-twitter { - background-color: #00acee; - border-color: #009ad5; -} -.btn-facebook { - background-color: #4868ac; - border-color: #314776; -} -.btn-pinterest { - background-color: #b62f26; - border-color: #b62f26; -} -{% endhighlight %} -2. Link this file into the `head` of `index.html` **underneath your link to bootstrap**. -3. What happens? Notice how in the first rule we've selected only those buttons that exist inside an element with `id=social-buttons`. -{% endexercise %} - -### Changing the background - -{% exercise %} -
        -
      1. -Change the background of the `jumbotron` to be the image `fruit-and-veg.png` by adding the css -{% highlight css %} -.jumbotron { - min-height: 600px; - background-image: url('images/fruit-and-veg.jpg'); - background-size: cover; - background-attachment: fixed; -} -{% endhighlight %} -
      2. - -
      3. -This doesn't look quite right. The problem is that the jumbotron is it is inside the div class='container'. You can change this by moving it inside: -{% highlight html %} -
        -
        - -
        -
        -{% endhighlight %} -Similarly you will now need to create new containers inside the div id='buzz' and div id='mission'. -
      4. -
      5. -Change the background color of the `mission` section to `rgba(32, 35, 41, 0.9)` and the font colour to `#ddd` -
      6. -
      -{% endexercise %} - - -### Navbar - -Browse through the [navbar section](http://getbootstrap.com/components/#navbar) of the Bootstrap docs. - -{% exercise %} -1. Look at the html for the [basic starter template](http://getbootstrap.com/examples/starter-template/). -2. Use it to add a navbar to your site. -2. Make it a `navbar-fixed-top`. You will need to add - - body { padding-top: 70px; } - - to `main.css`. -3. Add a search box to the navbar. Use the `pull-right` class to put it on the right hand side. -{% endexercise %} - -### Other things - -There are various other changes you will need to make your site look like the example. Try and figure out what these are by examining the html in the Developer tools. - -{% exercise %} -1. Make any other changes necessary to make your site look like [the example](http://code61.github.io/bootstrap_exercise/) -2. If you get stuck check by looking at the [gh-pages branch](https://github.com/code61/bootstrap_exercise/tree/gh-pages) on the github repo. -{% endexercise %} diff --git a/_sessions/c1s3/6_homework.md b/_sessions/c1s3/6_homework.md deleted file mode 100644 index be536d9..0000000 --- a/_sessions/c1s3/6_homework.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Homework ---- - -### Finishing off - -{% exercise %} -Finish off the bootstrap_exercise from class -{% endexercise %} - -### Personal site - -{% exercise %} -Continue work on your personal site. You might want to think about using Twitter Bootstrap! -{% endexercise %} - -### Further reading on CSS - -{% exercise %} -1. (Optional) Read [this article](http://coding.smashingmagazine.com/2009/08/17/taming-advanced-css-selectors/) which explains about CSS Specificity (and more). -2. (Optional) Read [this article](http://css-tricks.com/attribute-selectors/) on CSS selectors. -{% endexercise %} diff --git a/_sessions/c1s3/info.yml b/_sessions/c1s3/info.yml deleted file mode 100644 index 4531733..0000000 --- a/_sessions/c1s3/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 1 -strapline: Bootstrapping it up \ No newline at end of file diff --git a/_sessions/c1s4/1_recap.md b/_sessions/c1s4/1_recap.md deleted file mode 100644 index 459385d..0000000 --- a/_sessions/c1s4/1_recap.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Recap ---- -### CSS - -We're now going to add a separate CSS file to your first_site. (If you -already have one, that's fine - just add another one.) - -{% exercise %} -1. Create a new file in sublime text and save it as `main.css` in your - first_site folder. -2. Put a CSS rule in that file (e.g. `h1 {color: red}`) -3. Put a link to the file from the head section of your index.html file. -4. Make sure you can see the style when you open index.html in chrome. -{% endexercise %} diff --git a/_sessions/c1s4/4_google_analytics.md b/_sessions/c1s4/4_google_analytics.md deleted file mode 100644 index 2603e61..0000000 --- a/_sessions/c1s4/4_google_analytics.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Google Analytics ---- - -Google Analytics is an analytics service provided for free by Google. It allows you get an overview of how many people are visiting your site, where they come from, what they do on your site, and much more. - -### How it works - -To use Google Analytics you need to place a snippet of javascript (that they provide) on each of the HTML pages on your site. When a user visits the page, the javascript sends a message to the Google Analytics site logging the visit. - - -{% exercise %} -1. Set up a [Google Analytics](http://www.google.com/analytics/) account. You want to choose the default 'Universal Analytics' option. -2. In the Admin section, create a new account for your personal site. -3. Following the instructions, install the analytics code on all the pages of your site. -{% endexercise %} diff --git a/_sessions/c1s4/6_homework.md b/_sessions/c1s4/6_homework.md deleted file mode 100644 index 02d8fb2..0000000 --- a/_sessions/c1s4/6_homework.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -Continue to work on your `first_site` until it's something you can be proud of! -{% endexercise %} diff --git a/_sessions/c1s4/info.yml b/_sessions/c1s4/info.yml deleted file mode 100644 index 9125adf..0000000 --- a/_sessions/c1s4/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 1 -strapline: Analytics and HTML Forms \ No newline at end of file diff --git a/_sessions/c2s1/1_collaboration_publishing.md b/_sessions/c2s1/1_collaboration_publishing.md deleted file mode 100644 index b820338..0000000 --- a/_sessions/c2s1/1_collaboration_publishing.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Getting code from Github ---- - -### Git recap - - - -### Getting code from github - -In previous sessions we've used git to pull code down from github. We're going to start this session by doing the same again: - -{% exercise %} -1. Go to the command line and navigate to your `coding_course` folder -2. Clone the project [https://github.com/tomclose/cfgmt2013_first_site](https://github.com/tomclose/cfgmt2013_first_site): - - $ git clone https://github.com/tomclose/cfgmt2013_first_site toms_site - -{% endexercise %} - -You should now see a new file called `toms_site` in your `coding_course` folder, and be able to open `toms_site/index.html` in your browser. The clone operation has copied a local version of the repository onto your computer. - -Git will help you keep this local copy updated. If I've made some changes and pushed them up to github, you just need to run - - $ git pull - -to pull them down onto your laptop. - -{% exercise %} -1. Open `toms_site/index.html` in Sublime Text -2. Wait for me to make a change and push it to gihub -3. Pull down the changes and make sure you can see them in your browser: - - $ git pull -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c2s1/2_conflicts.md b/_sessions/c2s1/2_conflicts.md deleted file mode 100644 index 189ec83..0000000 --- a/_sessions/c2s1/2_conflicts.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Conflicts ---- - -The version on your laptop is stored in a fully functional git repository: you can make changes to the site and commit it if you want. What happens if we both make changes at the same time? - -{% exercise %} -1. Open `toms_site/index.html` in your code editor, and change the page heading (inside `<h1>`) to something of your choosing. (At the same time I'll also make a change). When you're done, commit your change to the local repository: - - $ git add --all - $ git commit -m "Changed heading" - -2. Wait while I push my own change to the `<h1>` element. -3. Pull down my changes - - $ git pull - -{% endexercise %} - -You should now have a message telling you that you have a merge conflict. This is because our two changes have been made at the same time, so git is unabled to work out which is the up-to-date one to keep. If you look in your file you should see things that look like - - - <<<<<<< HEAD -

      My Page

      - ======= -

      Tom C's page

      - >>>>>>> d76d5a62894057f9c5a4dce0fe5f25110eddd24f - - -To fix the merge conflict you need to edit this by hand, picking the version you want and then do: - - $ git add --all - $ git commit -m "Fixed conflicts" - -{% exercise %} -1. Delete the conflict markers (`<<<<`, `=====`, `>>>>`) from `index.html` (using Sublime text) -2. Delete the version of the heading that you don't want. -3. On the command line: - - $ git add --all - $ git commit -m "Fixed conflicts" - -4. To have a look at what you've just done: - - $ gitk --all - - or - - $ git log --pretty --graph --oneline - - You should see how the two versions branched and came back together. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c2s1/3_collaborating_using_github.md b/_sessions/c2s1/3_collaborating_using_github.md deleted file mode 100644 index 266e88f..0000000 --- a/_sessions/c2s1/3_collaborating_using_github.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Github collaboration ---- - -There are a few options for collaborating with others using Git. - -### One-way sharing - -As we all know, one-way sharing isn't really sharing at all. Even so, this is the easiest example to look at - in fact we've been doing it almost from the first session of the course. - -In one-way sharing, there is one 'master' repository on GitHub that everyone can read from, but only one person can write to: - -
      - -
      - - - -### Forking - -One of the options for sharing your changes with me, is for you to publish your repository too. I can then pull your changes down just as you pulled mine. - - -
      - -
      - -Notice that this situation is symmetric - my repositories are equivalent to yours. This makes it a suitable model for many open source projects, where the project maintainer might change over time. - -Github makes this model easy by providing a 'forking' button. Forking is a quick an easy way make a copy of my repository on GitHub so that you can then pull and push to it. - -### Sharing - -The other way or collaborating with git is the 'sharing' model: one person puts the repository on github and gives other people permissions, so you can all push to the same place. - -
      - -
      - -To do this on github, go to your forked landing page repository and click on 'Settings' on the right hand side. Then go to 'Collaborators' and add your team members' github usernames. - -
      - -You can find out more about these different workflow option from the [Git book](http://git-scm.com/book/en/Distributed-Git-Distributed-Workflows). \ No newline at end of file diff --git a/_sessions/c2s1/4_joint_project.md b/_sessions/c2s1/4_joint_project.md deleted file mode 100644 index 98bb695..0000000 --- a/_sessions/c2s1/4_joint_project.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Joint project ---- - -The purpose of this project is to create a shared html page to serve as a 'cheat sheet' for all the different commands you've learnt in the course so far (e.g. `ls`, `git add --all` etc.). You will need to be in groups of three. - -{% exercise %} -1. Person A should set up a new project on their laptop: - 1. Create a new folder called `group_cheatsheet` in your `coding_course` folder - 2. Create a file in that folder called `index.html` with some simple html in it. -2. Person A should then set it up as a git repository - - $ cd group_cheatsheet - $ git init - $ git add --all - $ git commit -m "Initial import" - -3. Person A creates a new repo on github. To do this you need to log in at [github.com](http://github.com) and select "Create a new repo". You should call the repository `group_cheatsheet`. -4. Person A should then push their code up to github following the instructions on github. You want to "Push an existing repository from the command line" - the instructions at the **bottom** of the page. You should end up pasting a command like - - # Warning: these commands won't work. You need copy the right ones from GitHub. - git remote add origin https://github.com/username/blah.git - git push -u origin master - - -5. Person A then needs to add everyone else as collaborators by going to `Settings > Collaborators` on the repo page -6. Everyone else should then clone the project: - 1. Go to the repo's github page - 2. Copy the `ssh` link from the box on the page - 3. In your `coding_course` folder do - - git clone paste_the_repo_link_here - -7. Person B should then download [Twitter Bootstrap](http://getbootstrap.com/) and put it in the `group_cheatsheet` folder -8. Meanwhile Person C should add more content to the page's html -9. Person B should add their changes and push up to github: - - git add . - git commit -m "Added twitter bootstrap" - git push - -10. Person C should then add their changes and try and push up: - - git add . - git commit -m "Edits to index.html" - git push - -11. This will probably fail, as C won't have B's changes. To fix this Person C needs to pull and merge (the merge will probably happen automatically if you haven't changed the same files). They should then push again: - - git pull - - # fix any merge conflicts if necessary, then add and commit the changes - - git push - -12. Continue to work on the cheatsheet together! - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c2s1/5_homework.md b/_sessions/c2s1/5_homework.md deleted file mode 100644 index afb4524..0000000 --- a/_sessions/c2s1/5_homework.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: Homework ---- - -### Tell us about your site - -{% exercise %} -Tell us about your first site by filling in [this form](https://docs.google.com/forms/d/1V8wA--rmXQ8KvPmpooLZEZPwl7Vp64-XRPlOea9rRlU/viewform). If you're still having problems getting it to display online or pointing your url to it, ask in the forum! -{% endexercise %} - -### Work on your group cheatsheet - -{% exercise %} -Continue to add information to your group cheatsheet. At the very least you should -1. Have a section for the basic command line commands. -2. Have a section for the basic git commands. -3. Have each pushed to the shared repository at least twice by next week. -{% endexercise %} - -### Learn to hate your track pad - -From now on, try to touch your mouse/trackpad as little as often - it will make you quicker and more effective. - -{% exercise %} -1. Practise using `Cmd-tab` (Mac) or `Ctrl-tab` (Windows) to move between programs. -2. Practise using `Cmd-space` (Mac) or ?? (Windows) to open programs by typing their names. -3. Practise using short cut keys: - - `Cmd-s` (Mac) or `Ctrl-s` (Windows) for saving - - `Cmd-r` (Mac) or `Ctrl-r` (Windows) to refresh the browser -{% endexercise %} - - -### Learn to love your editor - -Over the rest of the course you will be spending a lot of time in Sublime Text. Investing the time to learn to use it more effectively now will pay off! - -{% exercise %} -(Optional) Take a look through the [Sublime text screencasts](https://tutsplus.com/course/improve-workflow-in-sublime-text-2/) at Tuts+. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c2s1/info.yml b/_sessions/c2s1/info.yml deleted file mode 100644 index 1992a78..0000000 --- a/_sessions/c2s1/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 2 -strapline: Collaborative Coding \ No newline at end of file diff --git a/_sessions/c2s2/2_jquery.md b/_sessions/c2s2/2_jquery.md deleted file mode 100644 index db833f5..0000000 --- a/_sessions/c2s2/2_jquery.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: jQuery ---- - -This is meant to serve as a really quick introduction to jQuery - more to enable you to learn more, rather than to teach you anything in particular. - -### What is jQuery - -Javascript is the third main client side technology (along with HTML and CSS). Unlike HTML and CSS, which are mark-up languages, Javascript is a programming language - you can use it to do calculations (and pretty much anything you want!). - -jQuery is a **javascript library** that is useful for building interactive webpages. When you use jQuery, it's a bit like you're using a special version of javascript. - -jQuery is so common in webpages that, for beginners, 'learning javascript' has in many cases become 'learning jQuery'. This is the approach that we're going to take in this course. - -### Getting jQuery - -jQuery is just a javascript file that can be downloaded from the [jquery downloads page](http://jquery.com/download/). There are a couple of different versions - I'd go for the latest. For each version you can either get the normal code, which is useful for development, or the minified code, which has had all the space (and other stuff) taken out to make it as small as possibile, so it downloads quicker. - -Once you've downloaded the file and saved it in your site folder, you need to link to it in your page. For the time being we'll do this in the `head` (you can improve page-load times by moving your javascript to the bottom of the page, but we won't bother with this at the moment). - -{%highlight html%} - - - - - -{%endhighlight%} - -### Using jQuery - -You can do a lot of stuff with jQuery. Here we'll just look at the basics: selecting elements on the page and doing stuff with them. - -You can experiment with jQuery using the `Console` section of the Chrome developer tools. You will need to be on a page where jQuery is loaded (e.g. these course notes or the demo page you will download in the exercise). - -One of the nice things about jQuery is its ability to select elements via their CSS selectors. To select elements jQuery uses the `$()` function. For example: - -{% highlight javascript %} -$('li') // selects all the li elements on the page -$('li.important') // selects all the li with class="important" -$('#main-title') // selects the element with id="main-title" -{% endhighlight %} - -jQuery then has several ways of manipulating those elements: - -{% highlight javascript %} -$('h1').hide() -$('h1').show() -$('h1').css('color', '#f00') -$('h1').css('color', '#ff0') -$('h1').css('font-size', '80px') -$('h1').css('font-size', '8px') -$('h1').css('text-align', 'right') -$('h1').fadeOut() -$('h1').fadeIn() -{% endhighlight %} - -You can find out more about the options available to you in the [jQuery docs](http://api.jquery.com/). - -{% exercise %} -1. Clone down the jQuery demo code: - - git clone https://github.com/tomclose/jquery_intro.git - -2. Open `index.html` in Chrome. -3. Open the Chrome developer tools and switch to the `Console` panel. -4. In the console try the following: - - $('h1').hide() - $('h1').show() - $('h1').css('color', '#f00') - $('h1').css('color', '#ff0') - $('h1').css('font-size', '80px') - $('h1').css('font-size', '8px') - $('h1').css('text-align', 'right') - $('h1').fadeOut() - $('h1').fadeIn() - -5. Can you make the list items go green? -{% endexercise %} diff --git a/_sessions/c2s2/3_jquery_resources.md b/_sessions/c2s2/3_jquery_resources.md deleted file mode 100644 index 5dbb8bb..0000000 --- a/_sessions/c2s2/3_jquery_resources.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: jQuery resources ---- - -Obviously, we've only just scratched the surface of what's possible with javascript/jQuery. Things get a lot more interesting when you can create bits of javascript to be run in response to a user action. This allows you to build up interactions like "when the user clicks the submit button, check that their email is a valid email, if it isn't make the field go red and add the words 'email is invalid' at the bottom of the form". - -### Learning more jQuery - -We won't be spending any more time on jQuery this course, and will be moving onto backend stuff next term. If you want to learn more about jQuery you might want to try some of the following resources: - -* The [Codecademy jQuery course](http://www.codecademy.com/tracks/jquery) -* The [jQuery learning center](http://learn.jquery.com/) -* The [Codeschool jQuery course](https://www.codeschool.com/courses/try-jquery) - -### jsFiddle - -jsFiddle is a site which allows you to try out small bits of HTML, CSS and Javascript. It's a really useful tool for getting good help with javascript (and HTML/CSS) online: If you're having a problem: - -1. Create a jsFiddle showing what you've tried. -2. Post on StackOverflow describing the problem, with a link to the jsFiddle. - -People will be able to help you better if they can see the code themselves. Often they will respond with a working jsFiddle (as in [this example](http://stackoverflow.com/questions/11489037/add-and-remove-attribute-with-jquery)) diff --git a/_sessions/c2s2/4_ruby_check.md b/_sessions/c2s2/4_ruby_check.md deleted file mode 100644 index c0592c5..0000000 --- a/_sessions/c2s2/4_ruby_check.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Ruby check ---- - -Next term we're going to be looking at backend development in ruby. You will need to have ruby installed. You should check whether you have this now: - -{% exercise %} -1. On the command line (in any folder) type: - - ruby --version - - It should tell you the version of ruby that's installed. If it doesn't say anything you're in trouble! - -{% endexercise %} - -You can have a bit of a play with ruby now if you want: on the command line type `irb` (this stands for interactive ruby). You'll end up in a ruby session (a bit like if you've used Matlab). Try the following: - -{% highlight ruby %} -1+2 -3-4 -5*6 -10/5 -9/5 -9/5.0 -2**3 -2**19283 - -x = 5 -y = 6 -x + y - -(1..10).each {|n| puts n } - -{% endhighlight %} \ No newline at end of file diff --git a/_sessions/c2s2/info.yml b/_sessions/c2s2/info.yml deleted file mode 100644 index 4ac45c9..0000000 --- a/_sessions/c2s2/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Web Fundamentals 2 -strapline: A few extras \ No newline at end of file diff --git a/_sessions/c3prep/1_rails_installer.md b/_sessions/c3prep/1_rails_installer.md deleted file mode 100644 index 6efdddb..0000000 --- a/_sessions/c3prep/1_rails_installer.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: "Installing Ruby: Easy Way" ---- - -Ruby is a programming language that we will be the focus of the course. In order to run ruby programs on your computer you need to have the language, and various development tools, installed on your laptop. That's what we're going to do now. - -The easiest way to install ruby is to use the [railsinstaller](http://railsinstaller.org/), which will install ruby, Ruby on Rails, git and a few other things (don't worry if you already have git - it'll be ok!). Ruby on Rails is a framework for building web applications quickly and easily, built using Ruby. We won't actually be using Ruby on Rails in this course, but it's useful to have it for the future. - -It's important to realise that git, Ruby and Ruby on Rails are not 'programs' in the sense that you are probably used to. **There won't be any icons for ruby, git or Ruby on Rails**. They're the sort of programs you run from the command line, rather than applications that you click on. More on this later ... - -**If you're on a mac, the next tab has instructions on a different way to install ruby. Have a look at these before deciding which method you want to go ahead with.** - -{% exercise %} -Go to [http://railsinstaller.org/](http://railsinstaller.org/) and follow the instructions for your operating system (choosing all the defaults they give). You want the **Ruby 1.9** version. -{% endexercise %} - -### Windows notes: - -At the final stage, there will be a tick box asking if you want to "Configure git and ssh". Make sure this box is ticked. Follow the instructions and fill in your name and email (this is only used for your git commits). - -It will also tell you something about having copied your ssh key to the clipboard. This might or might not be true. In any case, don't worry as we're moving on to this next. - -### Mac notes: - -You will need to know which version of OS X you are running: 10.8 (Mountain Lion), 10.7 (Lion), or 10.6 (Snow Leopard). To check this click on the apple symbol in the top left of your screen and select 'About This Mac'. - - -### Did it work? - -{% exercise %} - -You should now have installed git and ruby on your laptop. Check it worked with the following steps: - -1. Open your command line: - * On a Mac open Terminal (Applications > Terminal) - * On Windowns open 'Command Prompt with Ruby on Rails' (this should have been installed by rails installer) -2. Type - - git --version - - It should look something like this - - $ git --version - git version 1.8.4 - $ - - If it doesn't print out your git version you have a problem - email your instructor! - -3. Type - - ruby --version - - It should look something like this - - $ ruby --version - ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.1] - $ - - If it doesn't print out your ruby version you have a problem - email your instructor! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3prep/2_homebrew_mac.md b/_sessions/c3prep/2_homebrew_mac.md deleted file mode 100644 index 33a3708..0000000 --- a/_sessions/c3prep/2_homebrew_mac.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: "Installing Ruby: Better Way" ---- - -These instructions are for **Mac only**. On Windows the Easy Way is the Better Way. - -### What's better about the Better Way? - -These instructions will take you through installing Ruby and git using an OS X package manager called [Homebrew](http://mxcl.github.io/homebrew/). Once you have Homebrew set up you will be able to quickly and easily install the vast majority of the (free, open-source) software you will need as a developer. Consider this an investment for the future! - -The first parts of the installation procedure is described in a post by Moncef Belyamani [here](http://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/). [Our Steps 1-3 correspond to their Steps 1-5. **We won't be doing their steps 6 onwards**.] If you get stuck, please check with these instructions. If you find things that don't work, please email your course instructor. - -### Step One: Installing Apple's Command Line Tools - -Homebrew works by providing automatic recipies to download and *compile* software for your computer. In order to compile software you need a compiler. Apple provides you with a compiler but doesn't install it on OS X by default. You will need to do this for yourself. Before you do this you should check you don't have it already. - -{% exercise %} -1. Open `Terminal` (e.g. from your `Application` folder) -2. Type - - gcc --version - -3. If this says something a bit like - - i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) - - you have a the gcc compiler installed and can skip to Step Two -4. If it says nothing, you need to install it. -{% endexercise %} - -If you don't have a compiler already you need to install Apple's Command Line Tools - either directly or by installing XCode. The options for doing this are described in the [Railsbridge Installfest](http://installfest.railsbridge.org/installfest/install_xcode). Those options are also covered in [Moncef's post](http://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/) as Step 1 - note the special instructions for those on Snow Leopard. - -{% exercise %} -If you don't have gcc, install it following one of the sets of instructions above. -{% endexercise %} - -### Step Two: Install Homebrew - -Once you have the compiler installed it should be mostly plain sailing. To install Homebrew - -{% exercise %} -1. Go to the [Homebrew homepage](http://mxcl.github.io/homebrew/) -2. Scroll down until you find the 'Install Homebrew' section and follow the instructions. It should be as simple as pasting - - ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)" - - into the terminal. -{% endexercise %} - -If you run into any problems have a check in Step 3 of [Moncef's post](http://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/). - -### Step Three: Install Git - -{% exercise %} -1. In the terminal type: - - brew update - brew install git - -2. Close the terminal programme and reopen it. -3. To check it worked, in the terminal type: - - git --version - - It should look something like this - - $ git --version - git version 1.8.4 - $ - - If it doesn't print out your git version you have a problem - ask in the forum! - -4. Configure your git details by typing - - git config --global user.name "Your Full Name" - git config --global user.email "Your Email Address" - - (replacing "Your Full Name" and "Your Email Address") -{% endexercise %} - -### Step Four: Install rbenv - -If you have a Mac, you actually already have ruby installed on your system. Unfortunately it's a really old version of ruby. As a developer it is useful to be able to have several versions of ruby on your system, so that you can switch versions between projects if necessary. [Rbenv](https://github.com/sstephenson/rbenv) (ruby environment) is a tool to help you do this. - -Note: if you have ever installed RVM you will need to uninstall it as it won't play well with rbenv. If you're following these instructions you probably haven't ever installed RVM. - -{% exercise %} -1. In the terminal type: - - brew install rbenv - brew install ruby-build - echo 'eval "$(rbenv init -)"' >> ~/.bash_profile - -2. Close the terminal and reopen it. -3. To check it worked, in the terminal type: - - rbenv --version - - It should look something like this - - $ rbenv --version - rbenv 0.4.0 - $ - -{% endexercise %} - -### Step Five: Install Ruby - -Having installed rbenv with homebrew, we will now use rbenv to install the latest version of ruby. - -{% exercise %} -1. In the terminal type: - - rbenv install 1.9.3-p392 - - This will download and install ruby version 1.9.2-p392 - -2. Then type: - - rbenv global 1.9.3-p392 - rbenv rehash - - This will set your system to use the new version of ruby by default. - -3. To check it worked, in the terminal type: - - ruby --version - - It should look something like this - - $ ruby --version - ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.1] - $ - -{% endexercise %} - -### Step Six: Install Rails - -You won't actually need rails this course, but now you've installed ruby it's easy to get it using *Rubygems*. Rubygems is ruby's excellent package manager, used for sharing projects written in ruby - more on this later in the course. - -{% exercise %} -1. In the terminal type: - - gem install rails - gem install bundler - -{% endexercise %} - - - - - - - diff --git a/_sessions/c3prep/3_ssh_keys.md b/_sessions/c3prep/3_ssh_keys.md deleted file mode 100644 index c51d0f8..0000000 --- a/_sessions/c3prep/3_ssh_keys.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: SSH keys ---- - -An SSH key gives you a way of connecting to a remote computer without having to type in a password everytime. In the course you will often be pushing code up to GitHub and other locations, and it can get annoying if you continually have to provide your password. - -In this step we will guide you through creating an ssh key and uploading it to GitHub. This is probably the most complicated step of the installation instructions. Good luck! - -
      -If you have 'GitHub for Windows' or 'GitHub for Mac' you might already have an ssh key set up. You can check this by logging in to github and clicking 'Account Settings > SSH keys'. If you see a key in the list, you're done and can skip the rest of this page. -
      - -GitHub itself provides excellent instructions for this step: [Github - Generating SSH Keys](https://help.github.com/articles/generating-ssh-keys). We'll be just providing a few notes to go with those instructions here. - -(You might see that GitHub recommends using a different connection method: https. We're going to stick with ssh as (a) it's good to know how to set up an ssh key and (b) it avoids messing around with the credential-helper.) - -### The basic overview - -What we're doing basically has two steps: - -1. Generate the key on your laptop -2. Upload the public part of the key to GitHub - -An SSH key comes in two parts. One part is public and can be given to anyone. The other part is private and should be stored safely on your laptop (when generating the key you can and should use a passphrase to protect it). Working together the two parts can accomplish two different purposes: - -* Anyone who has the public key can encrypt a message so that it can only be read using your private key. -* With your private key you can sign a message such that people with the public key can be sure you sent it. - -The keys work using the
      RSA algorithm. The whole system relies on the fact that it's easy to multiply large numbers but very hard to factorize them (to undo the multiplication). At least, it will be until someone builds a quantum computer, but that's another story ... - -{% exercise %} -Create and upload an SSH key to GitHub by following the [instructions on GitHub](https://help.github.com/articles/generating-ssh-keys) for your operating system. -{% endexercise %} - -### Notes for Windows users - -If you just ran RailsInstaller **you won't need to generate a key** - they did it for you! - -You will need to do **Step 1** on the [GitHub ssh key instructions](https://help.github.com/articles/generating-ssh-keys) then continue directly to **Step 3**. - -### Notes for Mac users - -For some reason RailsInstaller doesn't seem to generate the key for you on a Mac. You will need to do all the steps from the [GitHub ssh key instructions](https://help.github.com/articles/generating-ssh-keys). - - - diff --git a/_sessions/c3prep/4_command_line.md b/_sessions/c3prep/4_command_line.md deleted file mode 100644 index 0598ee5..0000000 --- a/_sessions/c3prep/4_command_line.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Meet the Command Line ---- - -The command line is a way to interact with your computer programmatically. If you are doing any software development you will need to get to grips with using the command line, as many of the programs you will use will be run from the it, instead of by clicking an icon. - -Note: when giving you instructions for the command line we will precede them with a `$` to represent the command prompt e.g. - - $ some_command - -**You shouldn't type the `$` sign - just the stuff after it.** So for the above instruction you would just type `some_command` into the command line. - - -### Moving around - -The first thing you will need to get used to is moving around. Start by printing the name of the directory you are in: - - $ pwd - -Then have a look at what's in that directory ( _list_ the contents): - - $ ls - -To move up a directory ( _change directory_ ) do - - $ cd .. - -To move back into the folder you just left do - - $ cd name_of_the_folder - -Your commandline will help you: tab can often be used to auto-complete names of files, the up arrow can be used to cycle through previous commands that you have typed. - -### Creating a directory - -You can do a lot more on the command line than just move around. We'll be using the command line a lot over the course. For the time being we just need to create a folder: - - $ mkdir coding_course - -Note: choosing names without spaces makes command line navigation easier. - -{% exercise %} -1. Open your command line: - * On a Mac open Terminal (Applications > Terminal) - * On Windows open Command Prompt with Ruby on Rails -2. Find out where you are: - - $ pwd - -3. See what is in the same folder: - - $ ls - -4. If you are on a Mac move into `Documents`: - - $ cd Documents - -5. Practice creating a new folder: - - $ mkdir my_new_folder - -6. Move into that folder: - - $ cd my_new_folder - -7. Move back up to the folder above - - $ cd .. - -8. Move back into the coding course folder. This time don't type out my_new_folder - just type out the first few letters and hit `Tab`: - - $ cd my_new_folder - -9. In the Finder (Mac) or My Computer (Windows) find the folder that you just created. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3prep/5_meet_ruby.md b/_sessions/c3prep/5_meet_ruby.md deleted file mode 100644 index a14ec45..0000000 --- a/_sessions/c3prep/5_meet_ruby.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Meet Ruby! ---- - -We'll be using [Codecademy](http://www.codecademy.com) to complement the work you're doing in class. In order to prepare for the first session, please take a look at the first two sections of the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby). - -{% exercise %} -1. Sign up for [Codecademy](http://www.codecademy.com). -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 1 and 2. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3prep/info.yml b/_sessions/c3prep/info.yml deleted file mode 100644 index 51b6d11..0000000 --- a/_sessions/c3prep/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Course Preparation -strapline: Prepare to ruby! \ No newline at end of file diff --git a/_sessions/c3s1/1_introducing_ruby.md b/_sessions/c3s1/1_introducing_ruby.md deleted file mode 100644 index 95bfe82..0000000 --- a/_sessions/c3s1/1_introducing_ruby.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Introducing ruby ---- - -Ruby is a programming language. It is different to HTML and CSS, which are just *markup* languages: in ruby you can do calculations. - -Ruby is an incredibly powerful and flexible language. It is a modern language - created in the 1990s by Yukihiro Matsumoto (Matz). A large part of his design philosophy is centered around optimizing for developer happiness - making a language that is a pleasure to program in. If you haven't already programmed in another language, you might not fully appreciate this, but - take it from someone who has - ruby is awesome! - -Ruby really shot to fame around 2005, due to the Ruby on Rails web framework. Ruby on Rails is a free, open-source web programming toolkit, which makes it really quick and easy to build web applications. Many top startups and sites (e.g. yellowpages.com, airbnb.com, github.com, gocardless.com, grouper.com) are built with ruby on rails - its rapid prototyping capabilities make it one of the go-to choices, especially for startups. The first version of Twitter was built in Ruby on Rails! - -In this course, we'll be leaning the basics of ruby, in a web development context. We won't be using ruby on rails, instead focussing on a simpler framework (called sinatra), which will give you a better understanding of what's going on behind the scenes and allow you to be far more productive with rails, when you come onto it later. - -## Interactive ruby: irb - -Ruby is an _interpreted language_. One of the great things about an interpreted language is that it's often possible to interact with the interpreter in real time. When you installed ruby, you also got a program called `irb` (interactive ruby), which allows you to interpret ruby on the command line. To start it you just type `irb` on the command line. - -{% highlight irb %} -001: > 2 + 2 - => 4 -002: > -{% endhighlight %} - -`2 + 2` is a ruby *expression*. The `=>` symbol tells you what *value* this expression evaluates to. The interpreter has converts expressions to values. - -If you just type the value `4` into irb, you will see that it will return `4` to you. - -{% highlight irb %} -001: > 4 - => 4 -002: > -{% endhighlight %} - -Like all values in ruby, `4` is also an expression - it just evaluates to itself. - -So far you've only seen values that are numbers. We'll come across some other values soon. - -## Comments - -In ruby, any part of a line that comes after a `#` is ignored. This is useful when you're writing complicated programs, as it allows you to write human-readable comments to document your code. - -{% highlight irb %} -001: > 2 + 2 # add together 2 and 2 - => 4 -002: > # this does nothing -003: > -{% endhighlight %} - -Notice how in line `002` above there is no `=>` and no return value; comments don't evaluate to anything - they're completely ignored. - -{% exercise %} -1. Pick a partner. -2. Open `irb` on one of your laptops. -3. For each of the following ruby expressions, try to agree what value you think they evaluate to. Check if you're right in irb. -{% highlight ruby %} -1 + 2 - -5 - 6 - -8 * 9 - -6 / 2 - -5 / 2 - -5.0 / 2 - -5 % 2 - -2.even? - -3.even? - -"hello " + "world" - -"Bob" * 3 - -"Bob" + 3 - -"don't shout".upcase - -"edam".reverse -{% endhighlight %} -{% endexercise %} - -{% exercise %} -4. (Challenge for pairs who finish early). What does the operation `^` do? E.g. - - 1 ^ 2 - - 2 ^ 5 - - 4 ^ 5 - - -{% endexercise %} diff --git a/_sessions/c3s1/2_exercise_summary.md b/_sessions/c3s1/2_exercise_summary.md deleted file mode 100644 index 22cf531..0000000 --- a/_sessions/c3s1/2_exercise_summary.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Exercise summary ---- - -Before we will move on to variables, we'll quickly look at a few of the things that you found out in the previous exercise: - -{% highlight ruby %} -> 6 / 2 -=> 3 -> 5 / 2 -=> 2 -> 5.0 / 2 -=> 2.5 -> 5 % 2 -=> 1 -{% endhighlight %} - -If you give ruby integers (whole numbers), it will do *integer division*. For example, `5 / 2` gives `2` as it is the largest whole number of times you can remove `2` from `5`. The partner to integer division is the remainder `5 % 2`, giving `1`. Together these two operations tell you that `2` goes twice into `5` with remainder `1`. If you give ruby decimals it will do normal division. **Everyone gets caught out by this at some point. You have been warned!** - -{% highlight ruby %} -> 2.even? -=> true -{% endhighlight %} - -The line above is actually pretty special. We've just asked the value `2` a question and it's responded. In programming terms, this works because `2` is an *object* - something that contains both data and *methods* that can query/manipulate the data. In this case, `even?` is the method that we called. In ruby **all values are objects**. This is unusual and isn't true in many other programming languages. We'll leave it at that for the time being, but you'll learn more about this later. - -{% highlight ruby %} -> "hello " + "world" -=> "hello world" -> "don't shout".upcase -=> "DON'T SHOUT" -{% endhighlight %} - -Here you met another third type of value: `"hello"` is a string. As you see here, you can add strings together. Like all ruby values, strings are also objects and therefore have methods. Here we used the `upcase` method, to change the string into uppercase. You can find out more about the methods that strings have in the [ruby docs](http://ruby-doc.org/core-2.1.0/String.html). - -{% highlight ruby %} -> "Bob" + 3 -TypeError: can't convert Fixnum into String -from (irb):1:in `+' -{% endhighlight %} - -Oh dear! Turns out that you can't add a string to an integer. Have another read of the message that irb gave you. Can you figure out what it is saying? When something goes wrong, ruby tries to be as helpful as it can. Learning to interpret the errors that ruby gives is an important part of learning to become a programmer. - -The ^ operator in the optional challenge is [bitwise exclusive or](http://en.wikipedia.org/wiki/Bitwise_operation#XOR). - diff --git a/_sessions/c3s1/3_variables.md b/_sessions/c3s1/3_variables.md deleted file mode 100644 index 13fe3b1..0000000 --- a/_sessions/c3s1/3_variables.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Names & Variables ---- - -So far we've used irb as a clever calculator, by working with values directly. Programming becomes a lot more powerful when you're able to give values **names**. - -A **name** is just something that you can use to refer to a value. In ruby you create a name by using the assignment operator, `=`. - -{% highlight ruby %} -age = 5 -{% endhighlight %} - - - - -age - -5 - - - - - - - - - - - -You can change the value associated with a name at any point. It doesn't even have to be the same type of value as the first value assigned to the name. Here we change the value associated with `age` to a string: - -{% highlight ruby %} -age = "almost three" -{% endhighlight %} - - - -age -“almost three” - - - - - - - - - - - -## Types of name - -There are various different types of name in ruby: - -* **local variables** e.g. `age`: Local variables begin with a lower-case letter. They're all we'll be using for now. -* **constants** e.g. `PI`: Any name that starts with a capital letter is deemed to be a constant. Ruby will complain if you try to change its value at a later date. -* **instance variables** e.g. `@name`: Instance variables start with a single `@` sign. They're used to store values inside objects. More later. -* **class variables** e.g. `@@count`: Class variables start with two `@@` signs. They're used to store values relevant to a set of objects. More on this later too. -* **global variables** e.g. `$last_error`: Global variables start with a `$` sign. They're available anywhere in your program. Relying on global variables is normally a bad idea. - -For the moment, we will just be using local variables. The important thing to take from the above tables is that **local variables must start with a lower-case letter**. - -## String interpolation - -String interpolation is a way of taking a variable and putting it inside a string. - -To write a string in ruby you can either use `'` or `"`. - -{% highlight ruby %} -string1 = 'hello' -string2 = "hello" -{% endhighlight %} - -In the code above, string1 and string2 are exactly the same. The difference between `'` and `"` is that `"` allows you to do **string interpolation**: - -{% highlight ruby %} -age = 5 -age_description = "My age is #{age}." -=> "My age is 5." -{% endhighlight %} - -Any ruby expression inside the `#{ }` will be evaluated and inserted into the string. Here we gave it the variable `age`, which points to the value `5`. As `5` is a value it evaluates to itself, so 5 is inserted into the string. - -{% exercise %} -1. With your partner, decide what each of the following instructions will do. Test to see if you're right in irb. - -{% highlight ruby %} -a = 1 - -a - -a+1 - -a - -a = a + 1 - -a - -b = "hello" - -b - -c = b.capitalize - -b - -c - -d = "hello" - -e = d.capitalize! - -d - -e - -name = "Dave" - -f = "Hello #{name}! " - -f - -name = "Sarah" - -f - -f * 5 -{% endhighlight %} - -{% endexercise %} -{% exercise %} -2. (Extension for pairs who finish early.)[Note: this exercise has a lot more to do with maths than programming. If you don't get it don't worry!] - - Consider the expression - ``` - x = (2 + 5*x - x**2)/5 - ``` - 1. Let `x = 1.1` - 2. Write `x = (2 + 5*x - x**2)/5` and then evaluate this multiple times (using the up arrow in irb) - 3. What happens? Can you explain why? - 4. Let `x = 1` and do the same thing. What happens and why? - -{% endexercise %} diff --git a/_sessions/c3s1/4_exercise_summary.md b/_sessions/c3s1/4_exercise_summary.md deleted file mode 100644 index 3b2fd05..0000000 --- a/_sessions/c3s1/4_exercise_summary.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Exercise summary ---- - -{% highlight ruby %} -> x = 1 -=> 1 -> x = x + 1 -=> 2 -{% endhighlight %} - -This might seem really obvious, but it's worth pointing out: `=` is an assignment operator; it means 'set name on the left equal to the value on the right'. It isn't the same equals as you see in maths! In maths `x = x + 1` doesn't really make sense -it's an equation with no (finite) solutions. In ruby `x = x + 1` makes perfect sense - just set `x` to be one more than it was before. - -{% highlight ruby %} -b = "hello" -c = b.capitalize - -b #=> "hello" -c #=> "Hello" - -d = "hello" -e = d.capitalize! - -d #=> "Hello" -e #=> "Hello" -{% endhighlight %} - -This example is pretty important. In the first case `capitalize` gives back "HELLO", but leaves the original string untouched. - - - -b -“hello” - - - - - - - - - -c -“Hello” - - - - - - - - - - - - -In the second case, we use the in-place version of `captialize!`. It changes the actual string that `d` is pointing to, and sets `e` to point there too. In ruby, methods often come in two flavours like this, with the `!` version modifying the original object in place. You could also try out `reverse/reverse!` and `upcase/upcase!`. - - - - - - - - - - - - - - - - - - - -d - -e -“Hello” - - - - -{% highlight ruby %} -> name = "Dave" -=> "Dave" -> f = "Hello #{name}! " -=> "Hello Dave! " -> f -=> "Hello Dave! " -> name = "Sarah" -=> "Sarah" -> f -=> "Hello Dave! " -{% endhighlight %} - -The above shows that *string interpolation happens when you write it down*. When you first write `f = "Hello #{name}! "` ruby immediately looks up `name` and bakes it straight into the string. Setting `name` to something differeny later on, won't change this. - -In the extra challenge, the expression gave an iterative approximation to sqrt(2). You can tell by rearranging and solving the equation, that any fixed point must be a sqrt of 2. In the final part, by giving it `x=1` you forced ruby to do integer arithmetic. If you're into that sort of thing, you might like to try and find the fixed points in this case! \ No newline at end of file diff --git a/_sessions/c3s1/5_sinatra.md b/_sessions/c3s1/5_sinatra.md deleted file mode 100644 index 2f7109a..0000000 --- a/_sessions/c3s1/5_sinatra.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Introducing sinatra ---- - -Sinatra is a lightweight web framework written in ruby. - -### Getting sinatra - -You can install sinatra on your laptop using [rubygems](http://rubygems.org/) - ruby's excellent package manager. When people write their own ruby libraries, they usually release them as a gem, so that others can quickly and easily install them. Sinatra is one of these libraries. To install it do: - - $ gem install sinatra - -at the command line. We will also need a few other rubygems, so install these too: - - $ gem install rack-test - -{% exercise %} -1. Install sinatra: at the command line run - - $ gem install sinatra - $ gem install rack-test - -2. Download the code for the session: - - $ git clone https://github.com/code61/sinatra_c3s1.git - - -{% endexercise %} - -## A simple ruby application - -So far, we've only used ruby in `irb`. If we're going to write ruby applications, we need to go beyond this. In this section, we're going to have some code written in a file (a `.rb` file) and we're going to run the whole file through the interpreter, using the `ruby` command. - -We're now going to look at a very simple ruby web application that uses sinatra. - -{% highlight ruby %} -# in app.rb: - -require 'sinatra' - -get '/' do - "hello" -end -{% endhighlight %} - -This file is very simple. The first line imports the `sinatra` library - this is what does most of the work here. The next bit tells sinatra how to respond to a certain type of request. In particular it says that if it receives a `GET` request to the root url it should send back the text "hello". - -To run this app you need to run the `app.rb` file using ruby. - - $ cd sinatra_c3s1 - $ ruby app.rb - == Sinatra/1.3.3 has taken the stage on 4567 for development with backup from Thin - >> Thin web server (v1.3.1 codename Triple Espresso) - >> Maximum connections set to 1024 - >> Listening on 0.0.0.0:4567, CTRL+C to stop - -Sinatra has started a webserver on your computer, which you can view in your browser. It will be displayed at the IP address `0.0.0.0` on port `4567`. `0.0.0.0` always points to the machine you are currently using. Another way of saying this is to use the word `localhost`. You will be able to view the site by typing one of the following into your browser address bar: - -* `0.0.0.0:4567` -* `localhost:4567` - -## Changing the app - -What just happened involved quite a lot of magic. Because of the line `require sinatra`, when you ran the file through ruby, the following happened: - -1. Sinatra started a webserver on your computer. -2. It used the code in your file to tell the webserver how to respond to a certain type of request. -3. The webserver sat on your computer, waiting for you to send it a request from your browser. - -Right now, you don't really need to understand how all this works. You just need to be able to understand the general overview and how to change certain bits. - -We're now going to change part of the app, so that the webserver says something different. - -There are two steps to this: - -1. Make a change in `app.rb`. -2. Restart the server, so it knows about the change you made. To do this, you need to first kill the server, using `Ctrl-c` in the terminal, and then restart it using `ruby app.rb`. - -{% exercise %} -1. Run the app. In the `sinatra_c3s1` directory: - - $ ruby app.rb - - Check you can see the page in your webbrowser at [localhost:4567](http://localhost:4567). -2. Make a change to `app.rb` so that it instead says "Hello there!". Check you can see the change in your browser (you will have to stop the server with `Crtl-C` then restart it again with `ruby app.rb`). -3. Try visiting a different url (e.g. [localhost:4567/about](http://localhost:4567/about)). What happens? -4. (Extension for those who finish early.) Have a look in the file `test1.rb`. What do you think the `test_default` at the end of the file does? Try running the test file from the command line: - - $ ruby test1.rb - - If the test passes, change the code back to see what happens when it fails. If it fails, try and make it pass! - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s1/6_basic_app.md b/_sessions/c3s1/6_basic_app.md deleted file mode 100644 index 04bd3b4..0000000 --- a/_sessions/c3s1/6_basic_app.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Basic app ---- - -### Taking parameters from the url - -Take a look at the following code: - -{% highlight ruby %} -# in app.rb: - -require 'sinatra' - -get '/' do - "hello" -end - -get '/:name' do - name = params[:name] - name -end -{% endhighlight %} - -The `/:name` is a URL matcher. It will match `/` followed by any word, for example `/tom`, `/gertrude` or `/this_isnt_a_name`. Sinatra will make this value available in something called the 'params hash'. You don't need to worry about this at the moment. The first line of the block, pulls the value out of the params hash and sets it to the local variable `name`. - -{% exercise %} -1. Open `app.rb` in Sublime text and uncomment the code at the bottom. -2. Change it so that visiting [localhost:4567/tom](http://localhost:4567/tom) shows "Hello Tom!" in the browser (and similarly for other names). [You will need to use string interpolation and a string method.] -3. (Extension.) Check your result by running `ruby test2.rb` in the console. -3. See if you can make it so that [localhost:4567/tom/bye](http://localhost:4567/tom/bye) shows "Goodbye Tom" in the browser (and similarly for other names). -4. (Extension - hard.) See if you can write another test in `test2.rb` to test your result. -{% endexercise %} - - diff --git a/_sessions/c3s1/7_homework.md b/_sessions/c3s1/7_homework.md deleted file mode 100644 index 945bb91..0000000 --- a/_sessions/c3s1/7_homework.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish the exercises from class. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 1 and 2. -3. Get a [Heroku](https://www.heroku.com/) account and upload an ssh key (see below). -{% endexercise %} - -### About Heroku - -[Heroku](https://www.heroku.com/) is a cloud-based web hosting solution, specifically designed for hosting web applications. It started out as a Rails host, but has since branched out into other frameworks (e.g. Sinatra, Node.js) and languages (e.g. Java, Python). - -They aim to completely manage your apps online infrastructure: you provide them with the code, they set it up and run it online. If you have a lot of users and want to scale your app up, they make it easy to allocate more resources so you can handle the increased traffic (for a price!). - -### Setting up an account - -Before you deploy your app to heroku you need to create an account. - -{% exercise %} -1. Sign up for an account at [Heroku](https://www.heroku.com/). -2. After you log in, download and install the heroku toolbelt. (This will allow you to interact with heroku from the command line). -{% endexercise %} - -### Setting up ssh with heroku - -The final part of the set up is to upload your ssh keys to Heroku. You might remember about ssh keys from the initial installation instructions: they're basically a way of identifying yourself to a server without typing in your password each time. - -The heroku toolbelt makes this very easy. On the command line (in any folder) type: - - $ heroku keys:add - -You can check it worked by typing: - - $ heroku keys - -It should list the ssh key that you just added. - -{% exercise %} -Upload your ssh key to heroku by running - - $ heroku keys:add - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s1/info.yml b/_sessions/c3s1/info.yml deleted file mode 100644 index f0fea99..0000000 --- a/_sessions/c3s1/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Introduction to Ruby -strapline: The basics \ No newline at end of file diff --git a/_sessions/c3s2/1_conditionals.md b/_sessions/c3s2/1_conditionals.md deleted file mode 100644 index 3ae5ffb..0000000 --- a/_sessions/c3s2/1_conditionals.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: If statements and comparisons ---- - -So far we've just used ruby to evaluate simple expressions. Coding becomes a lot more interesting when you can use your code for simple logic tasks: - -{% highlight ruby %} -if age >= 18 - "Here's the vodka you wanted." -else - "Move along please." -end -{% endhighlight %} - -The code within the `if` block will only be run if the statement is true. If the statement is false, the code in the `else` block will be run instead. - -### Comparisons - -There are some basic comparisons that will be useful when using if statments - -Symbol | Meaning ----- | ---- -`==` | Is equal to -`>` | Greater than -`<` | Less than -`>=` | Greater than or equal to -`<=` | Less than or equal to -`!=` | Not equal to - -Comparisons evaluate to `true` or `false`. - -{% exercise %} -Working with a partner, try out each of these comparisons in irb: -{% highlight ruby %} -4 == 5 - -'five'.length > 5 - -a = 20 -a <= 20 - -true >= false - -'aardvark' < 'anteater' - -'we' != 'done yet' -{% endhighlight %} -{% endexercise %} - diff --git a/_sessions/c3s2/2_post_requests.md b/_sessions/c3s2/2_post_requests.md deleted file mode 100644 index 2fbbe0a..0000000 --- a/_sessions/c3s2/2_post_requests.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Post requests revisited ---- - -Last time we looked at responding to `get` requests: - -{% highlight ruby %} -get '/' do - "Hello there!" -end -{% endhighlight %} - -As you know from the Introduction to Web Programming course, `GET` is only one of several types of web requests. Another is the `POST` request, which is commonly used for submitting data from a web form. - -Suppose we have the following HTML form: - -{% highlight html %} -
      - - - - -
      -{% endhighlight %} - -The form will submit via a `POST` request to the root url, `/`. We can respond to this using the following sinatra block: - -{% highlight ruby %} -post '/' do - name = params[:user_name] - age = params[:user_age] - - "Hello #{name}. You are #{age} years old." -end -{% endhighlight %} - -Note that, like the words matched in the url, the value of the `user_name` field is made available in the `params` hash. (If you want to have a look at the params hash you could put a `raise params.inspect` at the beginning of the method.) - -{% exercise %} -1. **Fork** the repository [https://github.com/code61/sinatra_c3s2](https://github.com/code61/sinatra_c3s2) (using the fork button on the top right of the repository page on github). -2. Clone down your fork of the repository onto your laptop. -3. Open the `sinatra_c3s2` project in Sublime Text and have a read through `app.rb`. See if you can predict what the app will do. -4. Run the app from the command line (`ruby app.rb`), to see if you were right. -5. (Optional) Add the line `raise params.inspect` right at the top of the post block. Restart the app and see what happens. When you've had a look, make sure you remove the line again! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s2/3_deploying.md b/_sessions/c3s2/3_deploying.md deleted file mode 100644 index 4233c6a..0000000 --- a/_sessions/c3s2/3_deploying.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: App deployment ---- - -We're now going to look at how to get the Sinatra app online, a process known as *deployment*. We're going to deploy the app to [Heroku](heroku.com), which offers easy hosting for a variety of web frameworks - all you need to do is push up a git repository, and they take care of everything else! - -You should have set up a heroku account and uploaded your ssh keys for homework. - -### Preparation - -There are a few files `sinatra_c3s2` that we need if we're going to deploy the app to heroku: - -* config.ru -* Gemfile - -`config.ru` contains the lines - -{% highlight ruby %} -require './app.rb' -run Sinatra::Application -{% endhighlight %} - -These lines are to tell Heroku which file to find your application (`app.rb`) and how to run it (using Sinatra). - -The `Gemfile` is a way of specifying which gems your project uses. Heroku needs to know this so it knows which libraries it needs to run your app. The `Gemfile` is also really helpful way of remembering yourself which gems you need and is invaluable when working with others. - -{% highlight ruby %} -# Gemfile - -source 'https://rubygems.org' - -gem 'sinatra' -{% endhighlight %} - -Along with rubygems, ruby has a tool called bundler. Bundler helps you manage your ruby gems. If you run `bundle install` it will look in the `Gemfile` and install any gems that you don't already have. - - $ bundle install - - will also create a `Gemfile.lock` which specifies the exact version of the gems (e.g. the sinatra library) that you are using. This means that heroku (and anyone else you're collaborating with using git) now knows exactly which gems you are using and can pick to use the same versions. You need to check this in to your repository: - - $ git add --all - $ git commit -m "Added Gemfile.lock" - -### Deploying to Heroku - -Once your app is prepared, the first thing you need to do is create a new empty heroku application. To do this you use the `heroku create` command: - - $ heroku create - Creating arcane-gorge-2129... done, stack is cedar - http://arcane-gorge-2129.herokuapp.com/ | git@heroku.com:arcane-gorge-2129.git - Git remote heroku added - -You'll see that it created an app for you. In my case the app is called `arcane-gorge-2129` and can be found at http://arcane-gorge-2129.herokuapp.com. It also added a git remote for you. - - $ git remote -v - heroku git@heroku.com:arcane-gorge-2129.git (fetch) - heroku git@heroku.com:arcane-gorge-2129.git (push) - origin git@github.com:code61/sinatra_project_1.git (fetch) - origin git@github.com:code61/sinatra_project_1.git (push) - - - -### Deploying - -You deploy your repository by pushing to this remote. Heroku will serve whatever is in the `master` branch. Here we push the `master` branch up to the `heroku` remote: - - $ git push heroku master - Counting objects: 11, done. - Delta compression using up to 2 threads. - Compressing objects: 100% (6/6), done. - Writing objects: 100% (11/11), 1.08 KiB, done. - Total 11 (delta 1), reused 0 (delta 0) - - -----> Ruby/Rack app detected - -----> Using Ruby version: ruby-1.9.3 - -----> Installing dependencies using Bundler version 1.3.2 - Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin --deployment - Fetching gem metadata from https://rubygems.org/.......... - Fetching gem metadata from https://rubygems.org/.. - Installing rack (1.5.2) - Installing rack-protection (1.5.0) - Installing tilt (1.4.1) - Installing sinatra (1.4.3) - Using bundler (1.3.2) - Your bundle is complete! It was installed into ./vendor/bundle - Cleaning up the bundler cache. - -----> Discovering process types - Procfile declares types -> (none) - Default types for Ruby/Rack -> console, rake, web - - -----> Compiled slug size: 25.0MB - -----> Launching... done, v3 - http://arcane-gorge-2129.herokuapp.com deployed to Heroku - - To git@heroku.com:arcane-gorge-2129.git - * [new branch] master -> master - -After you push, heroku automatically updates the app and launches it for you. You can now see the app by visiting the url (in this case http://arcane-gorge-2129.herokuapp.com). - -{% exercise %} -Deploy your `sinatra_c3s2` app to Heroku: - -1. Install your bundle to get a `Gemfile.lock`. In your `sintara_c3s2` directory run: - - $ bundle install - -2. Add your work (and new `Gemfile.lock`) to your repository: - - $ git add --all - $ git commit -m 'Added Gemfile.lock' - -3. Create a new heroku app: - - $ heroku create - -4. Push your work to Heroku - - $ git push heroku master - - (for subsequent updates you should be ok with just `git push heroku`). -5. Visit the url that heroku provide, to check that your app is running! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s2/4_templates.md b/_sessions/c3s2/4_templates.md deleted file mode 100644 index 31cfea8..0000000 --- a/_sessions/c3s2/4_templates.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: HTML templates ---- - -So far we've just returned text to the browser. It would be better if we could return proper HTML pages. We can do this by using **HTML templates**. - -{% highlight ruby %} -# in app.rb - -require 'sinatra' - -get '/' do - erb :form -end -{% endhighlight %} - -{% highlight html%} - - - - - - Barman 2.0 - - -
      -
      - - - - -
      -
      - - -{% endhighlight %} - -The line `erb :form` tells sinatra to look for a file called `form.erb` in a folder called `views`. It then processes that file using the `erb` (embedded ruby) templating language and returns the result to the user. - -The `form.erb` above isn't very interesting: it is just a static template and doesn't have any ruby embedded in it. Let's look at a slightly better example: - -{% highlight ruby %} -# in app.rb - -get '/' do - erb :form - -post '/' do - @name = params[:user_name] - @age = params[:user_age] - - erb :welcome -end -{% endhighlight %} - -{% highlight html %} - - - - - - hello - - -

      Hello <%= @name %>. You are <%= @age %> years old.

      - - -{% endhighlight %} - -The important bits are: - -* In `app.rb` we assign `params[:name]` to a special type of variable `@name`. The special type of variable is an *instance variable* which **has to begin with a single `@`**. -* We use the instance variable in the `views/greet.erb` inside a special erb tag `<%= ... %>`. The erb templater looks for these tags and interprets the inside as ruby. - -Sinatra emphasises *convention* over *configuration*: rather than specifying the exact place to find the template, you just give the name and Sinatra 'knows' where to look. This means you have to write less code in the long run, but also that you have to know the conventions before you start. - -
      -
      -

      Sinatra template summary

      -
      -
      -
        -
      1. You call a template with the line erb :template_name.
      2. -
      3. For this to work, you will need a template called template_name.erb in the views folder.
      4. -
      5. Instance variables (ones that start with @) will be shared with the template.
      6. -
      7. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable >
      8. -
      -
      -
      - - -{% exercise %} -1. Uncomment the bottom part of `sinatra_c3s2/app.rb` and comment out the top two blocks. -2. Restart your server and check you can see the new page `h1` sections. -3. Add twitter bootstrap to your templates, linking to the online hosted version as described on the [Bootstrap CDN](http://getbootstrap.com/getting-started/#download-cdn) section of the bootstrap docs. -4. Add a `div class='container'` around the page content, and add some styling to the `form` (see [here](http://getbootstrap.com/css/#forms)). -5. Add and commit your changes to your local git repo. -6. Deploy your changes: - - git push heroku - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s2/5_boolean_ops.md b/_sessions/c3s2/5_boolean_ops.md deleted file mode 100644 index e635e4a..0000000 --- a/_sessions/c3s2/5_boolean_ops.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Logical operations ---- - -It's often useful to combine various conditions: - -{% highlight ruby %} -if age < 12 || height < 1.2 - "You are allowed on the ride." -else - "Try a different helter-skelter. There's nothing for you here." -end -{% endhighlight %} - -In the above snippet of code, the `||` means OR. If the person is under 12 or is smaller than 1.2m they are allowed on the ride. - -### Logical operations - -Ruby has three ways of combining conditions: - -#### and (`&&`) - -If you use an `&&` the output is true only if both inputs are true. You can write this in terms of a *truth table*: - -{% highlight ruby %} -false && false #=> false -false && true #=> false -true && false #=> false -true && true #=> true -{% endhighlight %} - -#### or (`||`) - -If you use the `||` the output is true if at least one of the inputs is true. `||` means one or the other **or both**: - -{% highlight ruby %} -false || false #=> false -false || true #=> true -true || false #=> true -true || true #=> true -{% endhighlight %} - -### not (`!`) - -The `!` is not. It is a quick way of reversing the truth of the condition: - -{% highlight ruby %} -!false #=> true -!true #=> false -{% endhighlight %} - -{% exercise %} -1. Working with a partner, see if you can guess what the following expressions evaluate to. Test in `irb` to see if you're right. -{% highlight ruby %} -1 > 2 && 3 > 4 - -1==1 || 10 ==9 - -!(5<6) - -(1<=2 && 3>4) || (3 <= 4 && "ham") -{% endhighlight %} -{% endexercise %} diff --git a/_sessions/c3s2/6_truthy_falsey.md b/_sessions/c3s2/6_truthy_falsey.md deleted file mode 100644 index b73424b..0000000 --- a/_sessions/c3s2/6_truthy_falsey.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Truthy and falsey ---- - -In the last exercise you found out something interesting: - -{% highlight ruby %} -true && "ham" #=> "ham" -{% endhighlight %} - -Which is a bit weird. There are actually two things going on here: -1. The string `ham` is considered to be `true` -2. The overall statement evaluates to the last expression in it - -### Truthy and falsey - -In ruby there are only two values that are considered false: `false` and `nil`. We say that `false` and `nil` are *falsey*. - -Everything else is considered to be true. We say that all other objects are *truthy*. - -What we mean by 'considered to be true' is that if that value is used as a conditional in an `if` statement then the if code runs: - -{% highlight ruby %} -if 5 - x = 1 -else - x = 2 -end - -x #=> 1 -{% endhighlight %} - -In the above block of code, as `5` is truthy, the variable `x` is set to `1`. - -{% exercise %} -The bar is trialling a new initiative: Tuesdays is ladies night at the pub - no men allowed and all drinks are 2-4-1! They want you to update Bouncer 2.0 appropriately. - -1. Add select boxes for sex and day on the form. -2. Add new templates to be shown on ladies night to (a) turn away a customer if he is male (b) give them an extra drink if they are female. -3. Add the required logic to `app.rb` to make it all work. - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s2/7_homework.md b/_sessions/c3s2/7_homework.md deleted file mode 100644 index 312f323..0000000 --- a/_sessions/c3s2/7_homework.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish the final exercise from class. Spend a bit of time trying to make the app look more presentable and 'bouncer-like'. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 3 and 4. -{% endexercise %} - - -### Extension - -{% exercise %} -Change your sinatra app into something more interesting: - -- Add more options to the form. -- Make the logic in the views more complicated, so that you're using a few boolean operations. -- Change your app into a horoscope provider/career adviser/which-star-wars-character-are-you machine. -- Make it look nice, deploy it and show your friends. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s2/info.yml b/_sessions/c3s2/info.yml deleted file mode 100644 index f68e3ef..0000000 --- a/_sessions/c3s2/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Introduction to Ruby -strapline: Adding logic to app \ No newline at end of file diff --git a/_sessions/c3s3/1_arrays.md b/_sessions/c3s3/1_arrays.md deleted file mode 100644 index cca2fb6..0000000 --- a/_sessions/c3s3/1_arrays.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Arrays ---- - -An array is a way of storing a list of objects. Unlike in some other languages in ruby you don't need to specify which sort of object the array will hold - it can even hold objects of different types. - -Arrays are written with square brackets. -{% highlight ruby %} -my_array = [1,2,3] - -empty_array = [] # an array with no elements -{% endhighlight %} - - -{% exercise %} -Working with a partner, guess what each of the following expressions will give, then try them out in `irb`: - -{% highlight ruby %} -a = [3, 39, 1, 0, 5] - -a[1] -a.first -a[0] -a[5] - -a[-1] -a[-5] -a.last - -a[1..3] -a[1..-1] - -b = [] - -a.empty? -b.empty? -a.length -b.length - -a.include?(39) -a.include?(49) - -a.reverse -a # has this changed a? -a.reverse! -a # has this changed a? - -a.sort -a # has this changed a? -a.sort! -a # has this changed a? - -a = [1, 2, 3, 4, 5] - -a[3] = 6 -a # What is a now? - -a[7] = 7 -a # What else has been added? - -a << 9 # This one's important - you'll see it a lot - -{% endhighlight %} -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s3/2_array_summary.md b/_sessions/c3s3/2_array_summary.md deleted file mode 100644 index ab22380..0000000 --- a/_sessions/c3s3/2_array_summary.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Exercise summary ---- - -Here are some things you learnt in the last exercise: - -### Accessing elements - -* Arrays start from 0, so that the first elements is `a[0]` -* Arrays also allow indexing from the back, giving the last element as `a[-1]` -* If try to access beyond the end of the array it gives `nil` (instead of an error in other languages) -* You can access multiple elements by specifying a range, e.g. `a[1..-1]` is everything but the first element - -### Array methods - -Arrays have many useful (and largely self-explanatory) methods, including: - -* `empty?` - does the array have any elements, or is it the empty array `[]` -* `length` -* `include?(x)` - is `x` in the array -* `reverse`, `reverse!` - as with strings the `!` permanenty changes the array - -### Adding to an array - -* You can add to an array by setting a given element explicitly `a[5] = 6` -* If the array isn't long enough the gaps are filled with `nil`: - - a = [1, 2] - a[6] = 5 - a #=> [1, 2, nil, nil, nil, nil, 5] - -* You can also add to the end of an array by doing `a << 5`. This is very 'rubyish' and you'll see it a lot. diff --git a/_sessions/c3s3/3_iteration.md b/_sessions/c3s3/3_iteration.md deleted file mode 100644 index fc45414..0000000 --- a/_sessions/c3s3/3_iteration.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Iteration ---- - -Most programming language have some way of looping, or iterating, over a range of values. - -Ruby's approach to this is slightly unusual - instead of you taking elements from the array one-by-one, the ruby array *gives* the elements to you one-by-one. This might seem like a small distinction to make, but it has a significant effect on the feel of the ruby language and how you think about coding with it. - -The way you get an array to give you its elements is by calling its `each` method: - -{% highlight ruby %} -array = [1, 2, 3, 4, 5] -sum = 0 - -array.each do |n| - sum = sum + n -end - -sum #=> 15 -{% endhighlight %} - -The `each` method accepts a **block** - in the example above, this is everything between `do ... end`. - -* The `each` method sends the elements of the array one-by-one to the block. -* When the element arrives it is assigned to the variable `n`. -* The code on the inside of the block is then run. - -In the example above, each element is added to the `sum`. The example shows one method that you can use to sum the values in an array. - -Below is another example, which iterates over the elements of an array, separating them into one of two lists: - -{% highlight ruby %} -all_words = ['hello', 'how', 'are', 'you', 'today'] -long_words = [] -short_words = [] - -all_words.each do |word| - if word.length >= 5 - long_words << word - else - short_words << word - end -end - -long_words #=> ['hello', 'today'] -short_words #=> ['how', 'are', 'you'] -{% endhighlight %} - -Please note: the summing and categorising examples above can be made much neater with the use of the array methods `inject` and `select`. We'll leave that for another day though ... - -{% exercise %} -Take another look through the code examples above. Check you really understand how they work. Try them out in `irb`, to check they work as advertised! -{% endexercise %} - diff --git a/_sessions/c3s3/4_displaying_lists.md b/_sessions/c3s3/4_displaying_lists.md deleted file mode 100644 index b430709..0000000 --- a/_sessions/c3s3/4_displaying_lists.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Lists of data ---- - -So far we have only inserted single values and words into an already existing `erb` template. We will now look at using ruby to generate more of the template dynamically. - -Suppose you have a ruby array that you want to turn into an html list: - -{%highlight ruby%} -# in app.rb - -get '/fruit' do - @fruits = ["Bananas", "Apples", "Raspberries"] - erb :fruits_view -end -{% endhighlight %} - -We can do this by using the `@fruits` array's `each` method to iterate over the elements and put them into the page one-by-one. - -{% highlight html %} - -
        - <% @fruits.each do |fruit| %> -
      • <%= fruit %>
      • - <% end %> -
      -{% endhighlight %} - -You might notice that we've used a different type of erb tag for the `do ... end` block: `<% %>` instead of `<%= %>`. This is really important: - -* You need to use `<%= %>` if you want the result of executing that line of ruby to be added to the page. -* You need to use `<% %>` if you don't want the result of executing that line of ruby to be added to the page. - -Here, the bits we want adding are the elements of the array, so only they have the `<%= %>` tags. The code will cause the following html to be generated: - -{% highlight html %} -
        -
      • Bananas
      • -
      • Apples
      • -
      • Raspberries
      • -
      -{% endhighlight %} - -You can also use the same technique to generate tables and other html (lists of divs etc.). - -{% exercise %} -1. **Fork, then clone** the code for this exercise [https://github.com/code61/sinatra_c3s3](https://github.com/code61/sinatra_c3s3). -2. Add code to the body of `todo.erb`, so that the `@todos` display as an ordered list. -3. Add, commit and push your code to Github. -3. Add code to the body of `schedule.erb`, so that the items in the `@schedule` display as rows in a table. Note that `@schedule` is an *array of arrays* - you'll need to iterate over the first array, and within the loop use the normal ways of accessing elements of an array pull out the items. -3. Add, commit and push your code to Github. -4. Take a look at the `get '/rsvps'` block. Try the `CSV.read` bit in irb, to see what it does. Have a go at writing the code to categorise rsvps into acceptances/rejections and count them. -5. Update the `rsvps.erb` view, so that the right information is displayed. -3. Add, commit and push your code to Github. -{% endexercise %} diff --git a/_sessions/c3s3/5_sinatra_static.md b/_sessions/c3s3/5_sinatra_static.md deleted file mode 100644 index 0dda96a..0000000 --- a/_sessions/c3s3/5_sinatra_static.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Sinatra static assets ---- - -Last week we linked Twitter Bootstrap into your view templates, by linking to the online hosted version ``. What if we want to link to our own files? - -When we were building static sites, this was simple: we just created a `main.css` file in our site folder, and linked to it. The problem is that **a sinatra site folder is not like a static site folder**. We've already seen this: `app.rb` controls the url structure, not the folders in the app folder. (Just try going to '/app.rb' or '/views/index.erb'). Because of this, just dropping a `main.css` into the sinatra folder and trying to link to it won't work. - -Thankfully sinatra has a solution to this problem: if you create a folder called `public`, any files you put in there will be available from the root url. For example, if I have a file `public/main.css`, I can then link to this from my template files using ``. The two important things to note here are: - -1. I'm using a root-relative link (starting with a `/`). If you don't do this, you'll have problems if you ever call that template from a different url route. -2. I'm linking directly to `main.css`, **not** to `public/main.css`. - -
      -
      -

      Sinatra conventions

      -
      -
      -
        -
      1. Files inside the public folder will be served at the root of the site. This is where you should put your own stylesheets/images etc.
      2. -
      3. You call a template with the line erb :template_name.
      4. -
      5. For this to work, you will need a template called template_name.erb in the views folder.
      6. -
      7. Instance variables (ones that start with @) will be shared with the template.
      8. -
      9. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable >
      10. -
      -
      -
      - -{% exercise %} -1. Link the bootstrap stylesheet you'll find in `public/dist/css/bootstrap.css` into the `head` of `todo.erb` and `schedule.erb`. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s3/6_layout_files.md b/_sessions/c3s3/6_layout_files.md deleted file mode 100644 index 0a4496e..0000000 --- a/_sessions/c3s3/6_layout_files.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Sinatra layouts ---- - -One of the most important principles in software engineering is to stay [DRY](http://en.wikipedia.org/wiki/Don't_repeat_yourself): **don't repeat yourself**. - -The basic idea is that you don't want to be copying and pasting the same code into multiple places. If you're doing this, you're making a lot of work for yourself should you ever decide to change that code. - -One way of staying DRY that we'll meet soon is writing functions: if there's a task that you do repeatedly, write a function to put the logic for that task in one place and then call the function when you need to do the task. - -Another way, that we'll be looking at today, is in the form of layouts. - -### The Problem - -In the exercise today, you've been using a lot of erb view templates. You have 4 different templates, which all share the same basic outline: - -{% highlight html %} - - - - - Event Manager 2.0 - - - -

      Picture Unveiling Evening - Event Managment

      - - - - - -{% endhighlight %} - -{% highlight html %} - - - - - Event Manager 2.0 - - -

      Todo list

      - -
        - <% @todos.each do |todo| %> -
      • <%= todo %>
      • - <% end %> -
      - - - -{% endhighlight %} - -These files are almost the same - a lot of copy and paste has gone on. - -### The solution - -Sinatra gets round this problem by allowing you to have a `layout.erb` file in your `views` folder: - -{% highlight html %} - - - - - Event Manager 2.0 - - - - <%= yield %> - - - -{% endhighlight %} - -You can then write only the bits that change in the other two views: - -{% highlight html %} - -

      Picture Unveiling Evening - Event Managment

      - - -{% endhighlight %} - -{% highlight html %} - -

      Todo list

      - -
        - <% @todos.each do |todo| %> -
      • <%= todo %>
      • - <% end %> -
      -{% endhighlight %} - -Sinatra knows that if you have a file called `layout.erb` it should use that as a layout. If you call `erb :index`: - -* It takes the `layout.erb` file. -* It finds the bit where it says `<%= yield %>`. -* It inserts `index.erb` at that point. - -You can find more about Sinatra layouts on [the internet](http://lmgtfy.com/?q=sinatra+layouts). - - -
      -
      -

      Sinatra conventions

      -
      -
      -
        -
      1. If you have a file views/layout.erb Sinatra will treat it as a layout file: whenever it renders another template, it will try and insert the output into the <%= yield %> part of the layout file.
      2. -
      3. Files inside the public folder will be served at the root of the site. This is where you should put your own stylesheets/images etc.
      4. -
      5. You call a template with the line erb :template_name.
      6. -
      7. For this to work, you will need a template called template_name.erb in the views folder.
      8. -
      9. Instance variables (ones that start with @) will be shared with the template.
      10. -
      11. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable %>
      12. -
      -
      -
      - -{% exercise %} -*Refactor* your views: - -1. Create a layout file, containing the shared material from each view. -2. Remove the shared material from each view. -3. Check that the screens still look the same! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s3/7_homework.md b/_sessions/c3s3/7_homework.md deleted file mode 100644 index 4540280..0000000 --- a/_sessions/c3s3/7_homework.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Homework ---- - - -{% exercise %} -1. Finish the final exercise from class. If you have time, try and make the app look a bit nicer and practice deploying to heroku. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 5 and 6. -{% endexercise %} diff --git a/_sessions/c3s3/info.yml b/_sessions/c3s3/info.yml deleted file mode 100644 index f0d9fc4..0000000 --- a/_sessions/c3s3/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Introduction to Ruby -strapline: Arrays \ No newline at end of file diff --git a/_sessions/c3s4/1_introducing_hash.md b/_sessions/c3s4/1_introducing_hash.md deleted file mode 100644 index 9acc99c..0000000 --- a/_sessions/c3s4/1_introducing_hash.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Hashes ---- - -A `Hash` is ruby's basic *key-value store*: a place where you can store values, and look them up by a key. The `Hash` and the `Array` are ruby's two common ways of storing a collection of objects. The key differences between 'Hash' and 'Array' are: - -* In an `Array` objects are stored in order. You can think of an `Array` as a list. -* In an `Array` we reference objects by a numerical index. -* In a `Hash` there is no order on the objects. You can think of a `Hash` as a general collection. -* In a `Hash` objects are referenced by a `key`. The key can be a number or a word (or several other things). - -Here is an example of a simple hash: - -{% highlight ruby %} -character = {'name'=>'Bart', 'surname'=>'Simpson', 'age'=> 10, 'catchphrase' => 'Eat my shorts'} - -character['name'] #=> 'Bart' -character['catchphrase'] #=> 'Eat my shorts' -{% endhighlight %} - -In particular: - -* You write a `Hash` using the curly brackets `{ }`. -* Each element of the hash has a key e.g. `'name'` and a value e.g. `'Bart'`. -* When you write the hash you put the keys and values using the `=>` symbol: `key => value`. -* To pull values out of a hash you put the key inside `[ ]`. - -{% exercise %} -1. With your partner work through the expressions below. See if you can guess what each expression will do, then test by pasting into irb. -2. If you finish early, have a look at the 'Arrays and back' extension tab. -{% highlight ruby %} -h = {'one' => 1, 'two' => 2, 'three' => 3} - -# Accessing elements -# ------------------ - -h['one'] -h['two'] -h['four'] - -# Setting elements -# ---------------- - -h['five'] = 5 -h['one'] = 1.0 -h.delete('one') # What does this return? Does it change the hash? - -# Some methods -# ------------ - -h.length -h.empty? -h.keys -h.values -h.has_key?('one') -h.has_value?(7) - -# Iterating -# --------- - -h.each do |key, value| - puts "#{key}: #{value}" -end - - -# Combining -# --------- - -h1 = {'a'=>1, 'b'=>2} -h2 = {'b'=>3, 'c'=>4} - -h1.merge(h2) -h1 # what has this done to h1? -h1.merge!(h2) -h1 # what is h1 now? - - -# Using a hash for counting (extension) -# ------------------------- - -# start with an empty hash -h = {} - -['a', 'b', 'a', 'a'].each do |letter| - if h.has_key?(letter) - # if the letter is already in the hash, increase - # its count by 1 - h[letter] += 1 - else # letter isn't in the hash - # so put it in and set the count to 1 - h[letter] = 1 - end -end - -h # what is h now? - -# A slicker way to count (extension) -# ---------------------------------- - -# A slightly slicker way of doing this is -# using a hash with a default value: - -h = Hash.new(0) # 0 is the default value that is - # returned when the key is missing - -['a', 'b', 'a', 'a'].each do |letter| - h[letter] += 1 -end -{% endhighlight %} - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s4/2_summary.md b/_sessions/c3s4/2_summary.md deleted file mode 100644 index 90c828b..0000000 --- a/_sessions/c3s4/2_summary.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Exercise summary ---- - -In the last exercise you will have learnt a number of things about hashes. Here is a summary of the important points: - -### Accessing and setting elements - -{% highlight ruby %} -h = {'one' => 1, 'two' => 2, 'three' => 3} - -h['one'] #=> 1 -h['four'] #=> nil - -h['five'] = 5 -h['one'] = 1.0 - -h #=> {'one' => 1.0, 'two' => 2, 'three' => 3, 'five' => 5} -{% endhighlight %} - -* You access an element via its key: `h['one']` -* If the key isn't in the hash this will give `nil` -* You add new elements by setting their key -* If the key already exists its value will be updated - -### Methods - -Hashes have a number of methods, which behave as you would expect e.g. - -* `length` -* `empty?` -* `keys`, `values` -* `has_key?`, `has_value?` - -### Iterating - -Just like an `Array`, you can iterate over a `Hash` using the `each` method. Unlike array iteration, in hash iteration the block accepts two parameters: the key and the value: - -{% highlight ruby %} -h = {'one' => 1, 'two' => 2, 'three' => 3} - -h.each do |key, value| - puts "#{key} = #{value}" -end -{% endhighlight %} - -### Combining hashes - -Combining hashes is done by using the `merge` method. The values from the second hash are added to the first, replacing them if they already exist. You will often see this used in rails for specifying default options to a function: - -{% highlight ruby %} -# note how the first version of b gets overwritten -{'a' => 1, 'b' => 2}.merge({'b'=>3, 'c'=>4}) #=> {'a'=>1, 'b'=>3, 'c'=>4} - -# real life example -def print_names(opts) - default_opts = {'fancy_format' => true, 'max_length' => 20} - - # replace the defaults with options supplied - my_opts = default_opts.merge(opts) - - if my_opts['fancy_format'] - # .... - end - - #... -end -{% endhighlight %} - -The options example above is a common use of a hash in real life code. - -### Using a hash for counting - -One special use of a hash is for counting things. The following code is an example of how to do this. - -{% highlight ruby %} -h = {} - -['a', 'b', 'a', 'a'].each do |letter| - if h.has_key?(letter) - # if the letter is already in the hash, increase - # its count by 1 - h[letter] += 1 - else # letter isn't in the hash - # so put it in and set the count to 1 - h[letter] = 1 - end -end - -h #=> {'a' => 3, 'b' => 1} -{% endhighlight %} - -You can make this example a bit shorter by using a hash with a **default value**: normally a hash will return `nil` if the key isn't there, but we can set it up to return something else. In particular we'll set it up to return 0: - -{% highlight ruby %} -# set up a hash with default value 0 -h = Hash.new(0) - -['a', 'b', 'a', 'a'].each do |letter| - h[letter] = h[letter] + 1 -end - -h #=> {'a' => 3, 'b' => 1} -{% endhighlight %} - -If the letter isn't in the hash yet, the default value of 0 will be returned. Otherwise the current count will be returned. Either way, we just need to increase the value by 1. - diff --git a/_sessions/c3s4/3_symbols.md b/_sessions/c3s4/3_symbols.md deleted file mode 100644 index 187dbb4..0000000 --- a/_sessions/c3s4/3_symbols.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Symbols ---- - -Symbols are a bit like strings that can't be changed. They're primarily used to save space and time: - -* Every time you write a string in ruby it has to store a new copy of it in case it is changed. -* Every time you compare two strings it has to check every letter to see if they're the same. -* As symbols can't be changed, it allows ruby to only store them once. -* This makes it quick to compare, as you can just check to see if it's in the same storage location. - -So far we've used strings for our hash keys. As we write and compare hash keys a lot, it makes sense to use symbols instead. - -{% highlight ruby %} -"hello" -:hello -{% endhighlight %} - -{% highlight ruby %} -:hello.to_s -"hello".to_sym - - -"hello" << " world" -:hello << :" world" - -"hello".object_id - -:hello.object_id -{% endhighlight %} \ No newline at end of file diff --git a/_sessions/c3s4/4_email.md b/_sessions/c3s4/4_email.md deleted file mode 100644 index 8f8e3d3..0000000 --- a/_sessions/c3s4/4_email.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Sending email ---- - -Today we'll be looking at sending email from a ruby program. To do this we'll be using a library called [Pony](https://github.com/benprew/pony). Pony is a light-weight, simple library (in comparison more fully fledged options like [ActionMailer](http://guides.rubyonrails.org/action_mailer_basics.html)). After a small amount of configuration, it allows you to send emails with a single command. - -We'll be using a google account to send the email - you will need to input your username and password, and it will look like the email came from your gmail account. Using gmail is a good solution for a small test app like this. When you get bigger you will start hitting gmails sending limits, and you will want to investigate other solutions e.g. [sendgrid](http://sendgrid.com/) or [mandrill](http://mandrill.com/). For further options see the [heroku addons page](https://addons.heroku.com/). - -Before sending an email we need to set up some configuration. We do this by setting the `Pony.options` hash: - -{% highlight ruby %} -Pony.options = { - :via => 'smtp', - :via_options => { - :address => 'smtp.gmail.com', - :port => '587', - :enable_starttls_auto => true, - :user_name => 'yourusername', - :password => 'yourpassword', - :authentication => :plain, # :plain, :login, :cram_md5, no auth by default - :domain => "localhost.localdomain" # the HELO domain provided by the client to the server - } -} -{% endhighlight %} - -To send the email is then very simple: - -{% highlight ruby %} -Pony.mail(:to => 'example@example.com', :subject => "Wow - an email", :body=>"Hi. This is your program speaking. Bye.") -{% endhighlight %} - -You can find out more about the different options you can use on the [pony github page](https://github.com/benprew/pony). - -{% exercise %} -1. **Fork** and clone the code for this session: [https://github.com/code61/sinatra_c3s4](https://github.com/code61/sinatra_c3s4) -2. Install the gems (including `pony`): - - bundle install - -2. Copy and paste the contents of `development_pony_options.rb.sample` into a new file. Save this file as `development_pony_options.rb`. Fill in your gmail (or university) account details. -3. In irb type `require 'pony'`, then copy and paste in your updated options. -4. Send an email to yourself e.g.: - -{% highlight ruby %} -Pony.mail(:to => 'example@example.com', :subject => "Wow - an email", :body=>"Hi. This is your program speaking. Bye.") -{% endhighlight %} -5. Try running the sinatra app: `ruby app.rb`. -6. The form submission doesn't do anything at the moment. Can you work out what's wrong, and fix it? - -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s4/5_email_templates.md b/_sessions/c3s4/5_email_templates.md deleted file mode 100644 index 836bc3e..0000000 --- a/_sessions/c3s4/5_email_templates.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Email templates ---- - -So far the body of our email has only been a single line. What if we want a proper multi-line email? You can use `erb` templates for this! - -{% highlight ruby %} - Pony.mail( :to => @email, - :subject => "Congratulations, you added a fruit!", - :body => erb(:email, :layout => false) ) -{% endhighlight %} - -The important bit is `erb(:email, :layout => false)`, which tells sinatra to find `views/email.erb` and run it through erb (to replace any `<%= %>` tags). The `:layout => false` tells sintra to skip the normal layout file: we want to send the user the raw text, not an html page! The result is then used as the email's body. - -The template will look something like this: - - Hello there! - - <%= @name %> is a great fruit! - - Best, - - The FruitApp team - -{% exercise %} -1. Add the required line of code in the `post '/'` block, to send a welcome email to the new user. -2. Modify `views/email.erb` so that it (at least) contains the name of the person who just signed up. -2. (Optional extension) deploy your app to heroku. You will need to add the (free version) of the [sendgrid addon](https://addons.heroku.com/sendgrid) to allow you to send emails. -4. (Alternative extension) Clone down the project [https://github.com/code61/mailmerge](https://github.com/code61/mailmerge) and have a play! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s4/6_homework.md b/_sessions/c3s4/6_homework.md deleted file mode 100644 index 5013943..0000000 --- a/_sessions/c3s4/6_homework.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish off any exercises from class. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 7 and 8. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c3s4/8_hash_array_conversion.md b/_sessions/c3s4/8_hash_array_conversion.md deleted file mode 100644 index aad73ec..0000000 --- a/_sessions/c3s4/8_hash_array_conversion.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: (Ext) Arrays and back ---- - -This page is more advanced. This stuff is sometimes useful, but don't worry if you want to skip over it the first time through. - -### Converting to arrays and back - -You can convert a hash to an array using the `to_a` method and use the `Hash[ ]` syntax to convert it back: - -{% highlight ruby %} -h = {'a' => 1, 'b' => 2} - -h.to_a #=> [['a', 1], ['b', 2]] - -h2 = Hash[['a', 1], ['b', 2]] -{% endhighlight %} - -The `Hash[ ]` is also useful for creating a hash from arrays of keys and values (which is surprisingly useful). - -{% highlight ruby %} -keys = [1, 2, 3] -values = ['one', 'two', 'three'] - -# use Array#zip to get the arrays in the right format -zipped = keys.zip(values) #=> [[1, 'one'], [2, 'two'], [3, 'three']] - -h = Hash[zipped] #=> {1 => 'one', 2 => 'two', 3 => 'three'} -{% endhighlight %} - -{% exercise %} -(Optional) -1. Work through the following examples, copying and pasting into irb. -2. See if you can do the challenge at the end. -{% highlight ruby %} -# A few new ways to create a hash -# ------------------------------- - -h1 = Hash['a', 1, 'b', 2, 'c', 3] - -h2 = Hash[[['a',1],['b',2],['c',3]]] - - -# Converting to arrays (and back?) -# ------------------------------- - -h = {'a'=>1, 'b'=>2, 'c'=>3} - -a = h.to_a - -# How could you convert a back into h? - -h = {'one'=>1, 'two'=>2, 'three'=>3} - -keys = h.keys -values = h.values - -# How would you combine keys and values back into h? -{% endhighlight %} -{% endexercise %} diff --git a/_sessions/c3s4/9_hash_array_conversion_solution.md b/_sessions/c3s4/9_hash_array_conversion_solution.md deleted file mode 100644 index 5d0740c..0000000 --- a/_sessions/c3s4/9_hash_array_conversion_solution.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: (Ext) Exercise summary ---- -It's easy to convert a `hash` into an `array`. -{% highlight ruby %} -h = {'a'=>1, 'b'=>2, 'c'=>3} - -a = h.to_a -# => [["a", 1], ["b", 2], ["c", 3]] -{% endhighlight %} -To convert back from an `array` to a `hash`, use -{% highlight ruby %} -h=Hash[a] -# => {"a"=>1, "b"=>2, "c"=>3} -{% endhighlight %} - -You can unpack a `hash` into its keys and values with the `.keys` and `.values` methods - -{% highlight ruby %} -h = {'one'=>1, 'two'=>2, 'three'=>3} - -keys = h.keys -#=> ["one", "two", "three"] -values = h.values -#=> [1, 2, 3] - - -{% endhighlight %} - -and put it back together with - -{% highlight ruby %} -h = Hash[keys.zip(values)] - -# => {"one"=>1, "two"=>2, "three"=>3} -{% endhighlight %} - diff --git a/_sessions/c3s4/info.yml b/_sessions/c3s4/info.yml deleted file mode 100644 index ea94854..0000000 --- a/_sessions/c3s4/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Introduction to Ruby -strapline: Hashes and sending emails \ No newline at end of file diff --git a/_sessions/c4s1/1_motivating_functions.md b/_sessions/c4s1/1_motivating_functions.md deleted file mode 100644 index ad1728f..0000000 --- a/_sessions/c4s1/1_motivating_functions.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Improving code ---- - -This session we're going to be looking at ways to improve the code you write. In particular, we're going to see how to use *functions* to begin to separate out program logic into reusable chunks. - -### Why do we need functions? - -Take a look at this bit of code taken from a sinatra app: - -{% highlight ruby %} -@swimmer_first_name = @swimmer[:name].split.first -@swimmer_last_name = @swimmer[:name].split.last -@swimmer_dob = @swimmer[:dob] - -@cyclist_first_name = @cyclist[:name].split.first -@cyclist_last_name = @cyclist[:name].split.last -@cyclist_dob = @cyclist[:dob] - -@runner_first_name = @runner[:name].split.first -@runner_last_name = @runner[:name].split.last -@runner_dob = @runner[:dob] -{% endhighlight %} - -This code contains a lot of repetition. Some of the repetition might be unavoidable: we might really need to set up all those different instance variables to share with a view. Other bits aren't and will cause us problems in the long run. - -The duplication of the logic for extracting the first and last name is particularly problematic: - -* If we wanted to change the way a last name was extracted from a name (e.g to take into account names like 'Pierre de Fermat') we'd have to make changes in three places. -* The code is also cluttered and harder to make sense of than it needs to be: each time you read `.split.first` your brain has to convert that into 'find the first name'. As a programmer you will spend more time reading code than writing it, so these considerations are important. - -A nicer way to write this code would be to use `first_name` and `last_name` functions, that contain the logic for splitting up the name: - -{% highlight ruby %} -@swimmer_first_name = first_name(@swimmer[:name]) -@swimmer_last_name = last_name(@swimmer[:name]) -@swimmer_dob = @swimmer[:dob] - -@cyclist_first_name = first_name(@cyclist[:name]) -@cyclist_last_name = last_name(@cyclist[:name]) -@cyclist_dob = @cyclist[:dob] - -@runner_first_name = first_name(@runner[:name]) -@runner_last_name = last_name(@runner[:name]) -@runner_dob = @runner[:dob] -{% endhighlight %} - -{% exercise %} -1. Clone down the sinatra app for this session: [https://github.com/code61/sinatra_c4s1](https://github.com/code61/sinatra_c4s1). -2. Install the required libraries: `cd sinatra_c4s1` and then `bundle install`. -2. Familiarise yourself with the app, by looking through the code and running the app from the command line (`ruby app.rb`). -3. See if you can identify other places where the logic could be cleaned up. -{% endexercise %} diff --git a/_sessions/c4s1/2_functions.md b/_sessions/c4s1/2_functions.md deleted file mode 100644 index ef6ecb1..0000000 --- a/_sessions/c4s1/2_functions.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Functions ---- - -A *function* (or *method*) is a way of separating out a piece of programming logic so that you can use it elsewhere. - -### Defining and calling a function - -There are two steps in using a function - -1. *Define* the function: to define a function you need to give it a name and write the code contained in the function. -2. *Call* the function: when you use the function, we say that the function is being 'called'. Calling a function causes the code inside it to be run. - -{% highlight ruby %} -def first_name(full_name) - full_name.split.first -end - -first_name('Tom Close') #=> 'Tom' -first_name('Ashok Menon') #=> 'Ashok' -{% endhighlight %} - -In the example above the function takes a single *parameter* (in this case the full name that you want to split up). - -* When you call the function you give it the full name (e.g. `"Tom Close"`) as a string. -* The the variable `full_name`, that you specified in the function definition, is set to the name you provided. In this case this is equivalent to `full_name = "Tom Close"`. -* The statements inside the function body are then executed. -* The function *returns* the value of the last expression to be evaluated. - -{% exercise %} -1. **Fork** and clone down the exercises for this session: [https://github.com/code61/exercises_c4s1](https://github.com/code61/exercises_c4s1) -2. Install the gems you need - in the `exercises_c4s1` folder, run: `bundle install` -3. Open `names.rb` in sublime text. -4. Using the code above fill out the `first_name` function. -5. Open `irb` and load in the file by running `load 'names.rb'`. -6. Try the function out, by calling it in irb. -7. Close `irb` and run the tests we've provided for the function by running `rspec spec/first_name_spec.rb`. -8. Now try and write the body of the `last_name` function. Follow the same procedure of trying in irb, then running the test `rspec spec/last_name_spec.rb`. -9. (Ext) Improve your `last_name` function, so that it can cope with composite last names (treating everything after the first name as the last name). Test your solution by running `rspec spec/ext_last_name_spec.rb` -10. (Ext) Work through the functions in `dates.rb`. Test your solutions running the tests in files `spec/month_spec.rb`, `spec/last_digit_spec.rb`, `spec/penultimate_digit_spec.rb`, `spec/ordinal_suffix_spec.rb` and `spec/date_in_words_spec.rb`. -{% endexercise %} diff --git a/_sessions/c4s1/3_multiple_arguments.md b/_sessions/c4s1/3_multiple_arguments.md deleted file mode 100644 index ff8b67d..0000000 --- a/_sessions/c4s1/3_multiple_arguments.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: More about arguments ---- - -So far we've only looked at functions with a single argument. What if we want to have no parameters, multiple parameters or a variable number? - -### Functions with no parameters - -It is sometimes useful to have a function with no parameters, often for a task that you need to perform repetitively: - -{% highlight ruby %} -require 'csv' - -def load_data - # read data in from the csv file - data = CSV.read('tmp/students/data.csv') - - # remove the header row - data[1..-1] -end -{% endhighlight %} - -When you call a function with no parameters, you don't need to use brackets: - -{% highlight ruby %} - -load_data #=> [[..], [..], [..], ...] - -{% endhighlight %} - -

      [In fact you don't need brackets when you're calling a function with arguments either. For the time being we'll use them though, to keep things simple.]

      - -### Functions with multiple parameters - -Defining and calling a function with multiple parameters is just like defining and calling one with a single parameter: - -{% highlight ruby %} -def insult(word, strength) - "#{word.capitalize} off" + '!' * strength -end - -insult('goose', 4) #=> "Goose off!!!!" -{% endhighlight %} - -When you call a function with multiple parameters, you need to make sure you provide the right number, otherwise you'll get an error. - -{% highlight ruby %} -insult('badger', 4, 5) -#=> ArgumentError: wrong number of arguments (3 for 2) -#=> from (pry):2:in `insult' -{% endhighlight %} - -### Functions with optional parameters - -Sometimes it's useful to be able to supply a parameter if you want, but use a sensible default otherwise: - -{% highlight ruby %} -def i_love(thing = 'ruby') - "I love #{thing}!" -end - -i_love('coding') #=> "I love coding!" -i_love #=> "I love ruby!" -{% endhighlight %} - -{% exercise %} -1. Open `more_functions.rb` and begin to work your way throught the functions in the file. -2. For each function you write, reload the file into irb to try it out: `load 'more_functions.rb'` (run this **inside** `irb`). -3. For each function you write, run the appropriate test e.g.: `rspec spec/multiply_and_sum_spec.rb` (run this **outside** `irb`, on the command line). -4. If you get onto the `describe_result` function, you will need to start by writing your own test in `spec/describe_result_spec.rb`. (Do this by copying and pasting from another test, and make the appropriate changes.) -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s1/4_refactor_example.md b/_sessions/c4s1/4_refactor_example.md deleted file mode 100644 index d529f1c..0000000 --- a/_sessions/c4s1/4_refactor_example.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Refactoring ---- - -**Refactoring** is the act of restructuring a piece of code **without changing its behaviour**. Refactoring is very important in software development, as without it software projects quickly become unweildy and difficulat to work with. - -You're going to refactor the sinatra app, by completing the functions in the `helper_functions.rb` file. - -{% exercise %} -1. Open `app.rb` in Sublime Text. -2. Uncomment the commented out `post` block at the bottom, and comment out the other one. This is how we want the code to look, but currently the functions aren't there to make this work. -3. Uncomment the line `require './helper_functions'` at the top of `app.rb` -3. Open the file `helper_functions.rb` in Sublime Text. Complete the functions so that the app works as before. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s1/5_homework.md b/_sessions/c4s1/5_homework.md deleted file mode 100644 index 35b4848..0000000 --- a/_sessions/c4s1/5_homework.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish off any exercises from class. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 9 and 10. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s1/info.yml b/_sessions/c4s1/info.yml deleted file mode 100644 index 9e454b0..0000000 --- a/_sessions/c4s1/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Further Web Programming with Ruby -strapline: Better logic \ No newline at end of file diff --git a/_sessions/c4s2/1_function_recap.md b/_sessions/c4s2/1_function_recap.md deleted file mode 100644 index ca10fda..0000000 --- a/_sessions/c4s2/1_function_recap.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Revisiting functions ---- - -Last time we looked at splitting small bits of program logic out into functions. - -{% highlight ruby %} -# Extracts the first name from a full name. -# -# first_name('Tom Close') #=> 'Tom' -# first_name('Alan Jones') #=> 'Alan' -# -def first_name(full_name) - full_name.split.first -end -{% endhighlight %} - -This then allowed us to reuse this logic in different places: - -{% highlight ruby %} -post '/' do - @event = params[:event] - @swimmer = params[:swimmer] - @cyclist = params[:cyclist] - @runner = params[:runner] - - @event_name = event_name(@event) - @event_date = event_date(@event) - - @swimmer_first_name = first_name(@swimmer[:name]) - @swimmer_last_name = last_name(@swimmer[:name]) - @swimmer_dob = @swimmer[:dob] - - @cyclist_first_name = first_name(@cyclist[:name]) - @cyclist_last_name = last_name(@cyclist[:name]) - @cyclist_dob = @cyclist[:dob] - - @runner_first_name = first_name(@runner[:name]) - @runner_last_name = last_name(@runner[:name]) - @runner_dob = @runner[:dob] - - erb :tickets -end -{% endhighlight %} - -This form still isn't ideal though: - -* we have 3 competitors, but are passing around 9 different variables. If the `tickets` template were to become more complicated, things will only get worse. -* we have the `first_name` logic separated out, but the functions are separate from the data that they act on. We have to keep track of both these things throughout the program. - -Today we're going to be looking at a solution to this problem: we're going to be looking at **classes**, which will let us package up data with the functions that act on them. - -This will allow us to change the code so that it looks more like this: - -{% highlight ruby %} -post '/' do - @event = Event.new(params[:event]) - @swimmer = Person.new(params[:swimmer]) - @cyclist = Person.new(params[:cyclist]) - @runner = Person.new(params[:runner]) - - erb :tickets -end -{% endhighlight %} - -we'll then use this in the templates as follows: - -{% highlight erb %} - - - - - - - - - - - -
      First NameLast NameD.O.B
      <%= @cyclist.first_name %><%= @cyclist.last_name %><%= @cyclist.dob %>
      -{% endhighlight %} - -Instead of passing the `@cyclist` data to various functions, we're calling *methods* on a new `Person` object, that we've created. - -{% exercise %} -1. Clone down the sinatra app for the session: [https://github.com/code61/sinatra_c4s2](https://github.com/code61/sinatra_c4s2) -2. Install the gems for the app: `bundle install`. -2. Have a quick look at the commented out section at the bottom of `app.rb` to get an idea of where we're going. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s2/2_intro_to_classes.md b/_sessions/c4s2/2_intro_to_classes.md deleted file mode 100644 index 5382830..0000000 --- a/_sessions/c4s2/2_intro_to_classes.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Introducing classes ---- - -A class - -- you can view a class as a blueprint for a set of behaviour -- an instance of a class is called an object - -Classes are common to many programming languages. Languages that use classes to organise their logic are often referred to as Object-Oriented programming languages. Apart from ruby, other object-oriented programming languages include python, c++ and Java, meaning that the vast majority of code written at the moment is object-oriented code. - -Ruby is a more object-oriented language than most: in ruby every value (e.g. integers, strings, arrays, hashes, etc.) is an object. - -Have a look at the following use of a `Circle` object: -{% highlight ruby %} -c = Circle.new(10) - -c.radius #=> 10 -c.area #=> 314.2 -{% endhighlight %} - -The circle object holds the data, or **attributes**, of the circle (in this case just the radius) and has **methods** to perform operations (in this case calculating the area), using that data. - -We define the behaviour of this object using a class. You can view a class as a blueprint for a given type of object. We say that the objects that follow the blueprint that the class defines are *instances* of the class. - -{% highlight ruby %} -class Circle - def initialize(radius) - @radius = radius - end - - def radius - @radius - end - - def area - 3.142 * @radius * @radius - end -end -{% endhighlight %} - -There are a few things to note here: - -* The `initialize` method is run when you create the instance of the class e.g. `c = Circle.new(10)` -* Instance variables (beginning with `@`) are used to hold the attributes of the object e.g. `@radius`. Instance variables can be used inside any of the class's methods. - -{% exercise %} -1. Clone down the code for the session: [https://github.com/code61/exercises_c4s2.git](https://github.com/code61/exercises_c4s2.git) -2. Run `bundle install` to grab the required gems. -1. Have a look at `circle.rb` in sublime text: - - load it into irb: `load './circle.rb'` - - create a circle: `c = Circle.new(5)` - - check its radius and area: `c.radius` and `c.area` - - write the contents of the missing `circumference` method - - run the tests: `rspec spec/circle_spec.rb` (on the command line **not** irb) -2. Open `square.rb` in sublime text: - - write the missing methods - - load it into irb to check they work - - run the tests: `rspec spec/square_spec.rb` (on the command line) -3. Open `person.rb` in sublime text: - - write the missing methods - - load it into irb to check they work - - run the tests: `rspec spec/person_spec.rb` (on the command line) -4. (Ext) have a look in `mastermind.rb` and `guess.rb`. - - Write the missing methods in `guess.rb`. - - Run the tests to check it works. - - Use the `Guess` class you've just written to help write the missing methods in `mastermind.rb` - - Run the mastermind tests to check it works. -{% endexercise %} diff --git a/_sessions/c4s2/3_setters.md b/_sessions/c4s2/3_setters.md deleted file mode 100644 index 0f73541..0000000 --- a/_sessions/c4s2/3_setters.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: Changing attributes ---- - -So far we've just seen attributes that have been set when the class is **instantiated**. It's also possible to update attributes throughout the lifecycle of the object. Have a look at the following code: - -{% highlight ruby %} -class Child - def initialize(age) - @age = age - end - - def age - @age - end - - def age=(new_age) - @age = new_age - end - - def have_birthday - @age = @age + 1 - "You are now #{@age} years old!" - end -end -{% endhighlight %} - -It can be used as follows: - -{% highlight ruby %} -c = Child.new(5) -c.age #=> 5 - -c.age = 6 -c.age #=> 6 - -c.have_birthday #=> "You are now 7 years old!" -c.age #=> 7 -{% endhighlight %} - -{% exercise %} -Update your solution in `person.rb` to allow the `first_name` and `last_name` to be set independently, and have the `name` update accordingly: -{%highlight ruby %} -p = Person.new({:name => "Bart Simpson", :dob => "15/1/1990"}) - -p.name #=> "Bart Simpson" - -p.first_name = "Bartholomew" -p.name #=> "Bartholomew Simpson" -{% endhighlight %} -You might need to make changes to which attributes your class stores, to make this work. - -Test your work by running `rspec spec/person_update_spec.rb`. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s2/4_refactor.md b/_sessions/c4s2/4_refactor.md deleted file mode 100644 index e4385a1..0000000 --- a/_sessions/c4s2/4_refactor.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Putting it all together ---- - -We're now going to return to the sinatra app and use classes to refactor the app again. - -{% exercise %} -1. Gather up all the data and methods to do with people into a `Person` class: - - Copy your `Person` class from the exercise into `sinatra_c4s2/person.rb`. - - Uncomment the `require './person'` at the top of `app.rb`. - - Rewrite the person code in the `post` block to use your class. - - Change `views/tickets.erb` to call method on the objects you pass through. - - Check the app still works as before! -2. Gather up all the event-related code into a new `Event` class: - - Write the necessary code in `event.rb`. - - Uncomment the `require './event'` at the top of `app.rb`. - - Rewrite the event code in the `post` block. - - Change the views to use the objects. - - Check the app works as before. -{% endexercise %} diff --git a/_sessions/c4s2/5_homework.md b/_sessions/c4s2/5_homework.md deleted file mode 100644 index 2eed278..0000000 --- a/_sessions/c4s2/5_homework.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish off any exercises from class. -2. Do the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby) Sections 16 and 17. (If you have time, do the inbetween ones too!) -{% endexercise %} - -### Further reading - -We have only really begun to touch on what you can do with classes in ruby. There are really important concepts in object oriented programming (e.g. inheritance, class methods, class variables, mixins, etc.) that we haven't really mentioned at all. We'll meet some of these things in the next few weeks, but if you want a more comprehensive overview you can take a look at one of the following: - -- [http://phrogz.net/programmingruby/tut_classes.html](http://phrogz.net/programmingruby/tut_classes.html) -- [http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/](http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/) - -## Getting set up with MongoDB - -Next session we will look at storing information in a database. The database we'll be using is [MongoDB](http://www.mongodb.org/). - -To use mongodb you need to have it running on your laptop. The database will run on one of your localhost ports (like sinatra), so that other processes can connect to it. - -The preparation falls into four parts: - -1. Install MongoDB. -2. Start running the database. -3. Install the gems to allow ruby to connect to MongoDB. -4. Test your installation. - -We will look at these parts separately. - -### Install MongoDB - -If you installed `homebrew` ("The Hard Way", Mac only), your task is now easy. At the command line write: - - brew install mongo - -If you didn't install homebrew (i.e. try doing the above and it doens't work), you will need to [download MongoDB](http://www.mongodb.org/downloads) from the site and follow the installation instructions for your system. - -{% exercise %} -Install MongoDB either via - - $ brew install mongo - -or by downloading and installing from the [MongoDB website](http://www.mongodb.org/downloads). -{% endexercise %} - -### Start MongoDB running - -You can start MongoDB running from the command line: - - $ mongod - -You will need to **keep this command line open** and open a new one to continue the instructions. - -By default mongo will run on [localhost:28017](http://localhost:28017/). If you visit that link in your browser you should see a mongo stats page. - -{% exercise %} -1. Start MongoDB: - - $ mongod - -2. Check the service is running at [localhost:28017](http://localhost:28017/). -{% endexercise %} - -### Install the gems and test - -I've set up a project with the gems you need, so this should be straightforward: - -{% exercise %} -1. Clone the project: - - $ git clone https://github.com/code61/mongo_test.git - -2. Move into that folder and install the gems: - - $ cd mongo_test - $ bundle install - -3. Test your installation: - - $ ruby main.rb - - If you see the text "Everything worked ok!", you're good to go! -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s2/info.yml b/_sessions/c4s2/info.yml deleted file mode 100644 index 4a9c62a..0000000 --- a/_sessions/c4s2/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Further Web Programming with Ruby -strapline: Even better logic \ No newline at end of file diff --git a/_sessions/c4s3/1_intro_to_mongo.md b/_sessions/c4s3/1_intro_to_mongo.md deleted file mode 100644 index c093dcf..0000000 --- a/_sessions/c4s3/1_intro_to_mongo.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: About MongoDB ---- - - -In this session we will be using a database - a specialised piece of software for storing and retrieving data. Databases become important when you have large amounts of data, which you want to be able to access quickly and which you want to keep consistent. - -In the session we will be using two different, but related, pieces of software: - -* [MongoDB](http://www.mongodb.org/) the database. -* [Mongoid](http://mongoid.org/) a ruby library that we will use to interface with MongoDB. - -MongoDB is one of many different databases that we could have chosen. We went with MongoDB because it is fairly straight-forward to configure and quick to get going with. It is also fairly popular in the web community at the moment. - -MongoDB is a *NOSQL*, or *document-based*, database. In the past, the more traditional style *SQL*, or *relational*, databases were used in most applications. NOSQL databases have risen in popularity in the last year or two, in part due to their ability to offer increased performance in certain common scenarios, by allowing developers to bend the rigid SQL database structures. We will go into this in slightly more depth later in the course. For the time being, with data we're storing in the next few sessions it won't make much difference whether our db is SQL or NOSQL. - -### Using Mongoid - -Mongoid is a ruby library that allows you to interface with MongoDB. The idea is very simple - you can think of Mongoid as mapping **classes** in your application to **tables** in the database. Take a look at the following example: - -{% highlight ruby %} -class Athlete - include Mongoid::Document - - field :name, type: String - field :country, type: String - field :age, type: Integer - field :height, type: Integer - field :weight, type: Integer - field :sex, type: String - field :dob, type: Time - field :gold, type: Integer - field :silver, type: Integer - field :bronze, type: Integer - field :sport, type: Integer - field :events, type: Array - - def total_medals - gold + silver + bronze - end -end -{% endhighlight %} - -This is fairly similar to the classes we looked at last week - we have data and methods that act on the data. The two different parts are: - -* `include Mongoid::Document`: this activates this class as a mongoid-enabled class. -* The `field :name, type: String` etc.: these setup the getting and setting methods that we had to do by hand last week, and tell mongoid what sort of object it is, which is useful for storage purposes. - -You can use this class like this: -{% highlight ruby %} -a = Athlete.new -a.name = "Michael Phelps" -a.country = "US" -a.sport = "Swimming" -a.gold = 2 -a.silver = 2 -a.bronze = 0 - -a.name #=> "Michael Phelps" -a.total_medals #=> 4 -{% endhighlight %} - -This is not that exciting - we could have done all this last week. It gets more interesting when we start using some of the extra methods that Mongoid has added to the `Athlete` class: - -{% highlight ruby %} -# Let's save Michael in the database -a.save #=> true - -# How many athletes do we have? -Athlete.count #=> 1 - -# Let's pull Michael out again -a = Athlete.first #=> # - -# or -a = Athlete.find_by(:name => "Michael Phelps") #=> # - -{% endhighlight %} - - -### Starting MongoDB - -In order to use MongoDB in a ruby project, it first needs to be running on your computer. The command for this is - - $ mongod - -You will need to keep this command line open and continue the instructions in a new one. - -By default mongo will run on [localhost:28017](http://localhost:28017/). If you visit that link in your browser you should see a mongo stats page. - -{% exercise %} -1. Start MongoDB running on your laptop. -1. Clone down the code for the session: [https://github.com/code61/sinatra_c4s3](https://github.com/code61/sinatra_c4s3) -2. Run `bundle install` to get the required gems. -3. Open up `irb`. -4. Type `require './utils'` (this loads in the `Athlete` class and sets up your MongoDB connection). -5. Try the following -{% highlight ruby %} -a = Athlete.new -a.name = "Michael Phelps" -a.country = "US" -a.sport = "Swimming" -a.gold = 2 -a.silver = 2 -a.bronze = 0 - -a.name -a.country - -a.save - -Athlete.count -b = Athlete.first - -b.name -b.name = "Tom Close" - -a.name # has this updated? - -b.save -a.name # has it updated now? - -a.reload -a.name - -# different way of creating an athlete, using a hash -c = Athlete.new(:name => "Chad Le Clos", :country => "South Africa", - :sport => "Swimming", :gold => 1, - :silver => 1, :bronze => 0 ) -c.save - -d = Athlete.find_by(:name => "Chad Le Clos") -{% endhighlight %} -{% endexercise %} diff --git a/_sessions/c4s3/2_searching_and_sorting.md b/_sessions/c4s3/2_searching_and_sorting.md deleted file mode 100644 index 5be787e..0000000 --- a/_sessions/c4s3/2_searching_and_sorting.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Searching and sorting ---- - -One thing that databases are good at is searching for records. Mongoid allows you to search for records in various different ways: - -{% highlight ruby %} -Athlete.find_by(:name => "Michael Phelps") - -Athlete.find_by(:gold => 2) # returns the first one it finds - -Athlete.where(:gold => 2) # returns a 'collection' with all of them - -# you can do lots of things with collections e.g. counting -Athlete.where(:gold => 2).count -# or iterating -Athlete.where(:gold => 2).each do |a| - puts a.name -end -# or summing -Athlete.where(:gold => 2).sum(:age) -# or turn it into an array -Athlete.where(:gold => 2).to_a - -# searching on multiple things at once -Athlete.where(:gold => 2, :bronze => 3) -# or -Athlete.where(:gold => 2).where(:bronze => 0) - -# searching on conditions -Athlete.where(:gold.gte => 2) - -{% endhighlight %} - -You can find further examples in the [Mongoid docs](http://mongoid.org/en/mongoid/docs/querying.html#queries). - -### Sorting - -You can also get the database to return things to you sorted: - -{% highlight ruby %} - -# these both return collections -Athlete.order_by(:age.asc) -Athlete.order_by(:age.desc) - -# you can then do things like -# .. take the first 1 -Athlete.order_by(:age.asc).first - -# .. or the first 10 -Athlete.order_by(:age.asc).limit(10).to_a - -{% endhighlight %} - - -{% exercise %} -1. Open `irb` and do `require './utils'`. -2. Call the function `load_athletes`. This loads in all the athletes from London 2012. -3. Answer the following questions: - 1. How many athletes were there? - 2. How many women? How many men? - 3. Who was the oldest athlete? - 4. Who was the youngest? - 4. How many people won at least 1 gold? - 5. What was the average age? (Your answer should have decimal places..) - 6. Who got the most golds? - 7. Who was the 10th oldest athlete? -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s3/3_Exercise_answers.md b/_sessions/c4s3/3_Exercise_answers.md deleted file mode 100644 index c8fb4b6..0000000 --- a/_sessions/c4s3/3_Exercise_answers.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Exercise answers ---- - - 1. How many athletes were there? - 2. How many women? How many men? - 3. Who was the oldest athlete? - 4. Who was the youngest? - 4. How many people won at least 1 gold? - 5. What was the average age? (Your answer should have decimal places..) - 6. Who got the most golds? - 7. Who was the 10th oldest athlete? - - -{% highlight ruby %} -Athlete.count -#=> 10384 - -Athlete.where(:sex=>"M").count -#=> 5756 - -Athlete.where(:sex=>"F").count -#=> 4628 - -Athlete.order_by(:age.desc).first.name -#=> "Hiroshi Hoketsu" - -Athlete.order_by(:age.desc).last.name -#=> "Adzo Kpossi" - -Athlete.where(:gold.gt => 0).count -#=> 162 - -Athlete.sum(:age)/Athlete.count.to_f -#=> 26.06885593220339 - -Athlete.order_by(:gold.desc).limit(11).each do |a| - puts a.name - puts a.gold -end -#=>Yannick Agnel -#=>2 -#=>Bo Bae Ki -#=>2 -#=>Elisa Di Francisca -#=>2 -#=>Gabrielle Douglas -#=>2 -#=>Missy Franklin -#=>2 -#=>Michael Jung -#=>2 -#=>Ryan Lochte -#=>2 -#=>Michael Phelps -#=>2 -#=>Allison Schmitt -#=>2 -#=>Dana Vollmer -#=>2 -#=>Shiwen Ye -#=>2 - - Athlete.order_by(:age.desc)[9].name - => "Irada Ashumova" - -{% endhighlight %} diff --git a/_sessions/c4s3/4_mongo_with_sinatra.md b/_sessions/c4s3/4_mongo_with_sinatra.md deleted file mode 100644 index 0e9db89..0000000 --- a/_sessions/c4s3/4_mongo_with_sinatra.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Mongo with sinatra ---- - -### Setting up Sinatra to work with Mongoid - -To get sinatra to work with Mongoid you will need to do the following things: - -1. Add `gem 'mongoid'` to your Gemfile (and `bundle install`). -2. Create a `mongoid.yml` file with your Mongoid settings (see below). -3. Load mongoid and connect to the database - -For local development, you will also need to **make sure MongoDB is running on your laptop** - type `mongod` at the command line. - -##### Mongoid.yml - -The mongoid.yml file specifies the options you need to connect to a MongoDB database. The following should work: - -{% highlight yaml %} -development: - sessions: - default: - hosts: - - localhost:27017 - database: london2012 - options: - raise_not_found_error: false - -production: - sessions: - default: - uri: <%= ENV['MONGOHQ_URL'] %> - options: - raise_not_found_error: false - -{% endhighlight %} - -There are two sections, describing different databases to connect to in development and production. You should **change the development database name** from 'london2012' to something suitable for your project. If you fail to do this, your code will still run, but eventually you'll run into problems as data from one project turns up in another. - -The production section is set up to use MongoHQ on Heroku (see below). Sinatra can find out which environment it is running in by checking the `settings.environment` variable, which will return `:production` on Heroku and `:development` on your local machine. Mongoid uses this to know which part of the `mongoid.yml` file to look at. - -##### Loading libraries and connecting - -You also need to load the relevant libraries in `app.rb` and setup a database connection. The following code does this: - -{% highlight ruby %} -# in app.rb -require 'sinatra' -require 'mongoid' -require 'json' - -# Setup database connection -Mongoid.load!("mongoid.yml") - -get '/' do -# etc. etc. -{% endhighlight %} - -As well as the 'mongoid' and 'sinatra' libraries, you also need to include 'json', which mongoid uses to store objects in the database. - -The `Mongoid.load!` line is the one which uses the sinatra environment to decide which part of `mongoid.yml` to look at. - -### Mongoid on Heroku - -If you use the `mongoid.yml` from above, you'll be pretty much ready to go on Heroku. The only thing you'll need to do is to add the [MongoHQ Add-on](https://devcenter.heroku.com/articles/mongohq). You can do this by logging into Heroku. - -{% exercise %} -1. Run app.rb and take a look at the site in your browser. -2. Modify the application so that the 'oldest' link displays the 20 oldest athletes. -3. Make changes so that the 'youngest' link displays the 20 youngest athletes. -4. Add at least 2 more stats pages of your choosing. -5. (Optional) Return to `sinatra_c3s4`. Set your app up with mongoid, so that when people sign up it stores their names and emails. You will need to: - * Follow the steps above to add mongoid to the sinatra app. - * Create a mongoid-enabled `User` class, to store the data. - * Add a `/list` route for admins to see the list of people who've signed up. - * Push it to heroku. - * You can see a working app [here](http://aqueous-earth-3131.herokuapp.com/). If you get stuck, you can find the code [here](https://github.com/code61/mongo1/tree/solution). -{% endexercise %} diff --git a/_sessions/c4s3/5_homework.md b/_sessions/c4s3/5_homework.md deleted file mode 100644 index f8d3ba7..0000000 --- a/_sessions/c4s3/5_homework.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Homework ---- - -{% exercise %} -1. Finish off any exercises from class. -2. Finish off anything you haven't done from the [Codecademy Ruby track](http://www.codecademy.com/tracks/ruby)! -{% endexercise %} diff --git a/_sessions/c4s3/info.yml b/_sessions/c4s3/info.yml deleted file mode 100644 index b50ac09..0000000 --- a/_sessions/c4s3/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Further Web Programming with Ruby -strapline: Intro to MongoDB \ No newline at end of file diff --git a/_sessions/c4s4/2_intro_to_rails.md b/_sessions/c4s4/2_intro_to_rails.md deleted file mode 100644 index 7884a0c..0000000 --- a/_sessions/c4s4/2_intro_to_rails.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Intro to Rails ---- - -Rails is a web framework written in ruby. It is similar to Sinatra, except it does a lot more for you. Rails is great as it makes it possible to build serious web applications while you continue to learn about web development. - -A lot of your time as a new rails programmer will be spent figuring out how all the pieces fit together. It can seem daunting at first, however there are a huge number of excellent blog posts/tutorials/videos out there which will make your task much easier. In this session we will go through the steps involved setting up a new rails application and spend a bit of time looking around the application that is created. - -In this session we will be creating a Rails 4.0 application. Rails 4.0 is the latest version of rails and was released a few months ago. When looking at advice on the internet it's important to be aware that some things have changed since Rails 3, and so some things may no longer apply. - -One of the nice things about rails is it does a lot of work for you. We'll start by creating a new rails project using the `rails new` command: - - $ rails new project_manager - -This command has created a new folder called `project_manager` and filled it with the files for a basic rails application. As part of this it will have created a `Gemfile` to manage the dependencies and as the last step will run `bundle install` to download them all. - -Let's have a quick look in this new folder: - - $ cd project_manager - $ ls -a - .gitignore - Gemfile - Gemfile.lock - README.rdoc - Rakefile - app - bin - config - config.ru - db - lib - log - public - test - tmp - vendor - -You'll notice a couple of files that you recognise from sinatra: `Gemfile`, `Gemfile.lock` and `config.ru`. Rails has also created a `.gitignore` file for you so that files that shouldn't be placed in version control aren't. - -Rails has also created a load of folders for you, mostly with other files and folders inside. We won't worry about all of these at the moment, but will come back to them later on. - -We can run this skeleton application by starting the rails server (similar to `ruby app.rb` in Sinatra). To do this type - - $ rails server - -This will probably start rails running at [localhost:3000](http://localhost:3000). When you visit that link you'll find a default rails page telling you some information about your new application. - -### Generating a model - -Models are the 'the things our system is about'. For our project manager application, one of the models we will be working with will be the `task` model. A user will create tasks, others will be able to see the tasks and then mark them as created when they're done. We will create the files for the task by generating a scaffold: - - $ rails generate scaffold task name:string due_date:date description:text project:string completed:boolean - -The `rails generate scaffold` command tells rails to set up everything to do with the `task` model that we're creating (more on this later). The name of the thing that you're creating (`task` in this case) should always be **singular**. The final part of the command `name:string due_date:date description:text` tells rails what attributes the model should have and what type they are. The possibilities for the types are: - - :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean - -an up-to-date list of which can be found in the [rails docs](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column). - -Among other things the `generate scaffold` command will have set up a *database migration* to set up the database table for tasks. As a final step we need to create that tale in the database: - - $ rake db:migrate - -Once you have **restarted the server** you should now be able to visit [localhost:3000/tasks](http://localhost:3000/tasks) in the browser and create a task. - - -{% exercise %} -0. Before you start check that you're running rails 4.0: - - $ rails -v - Rails 4.0.0 - -1. In your `coding_course` folder set up a new rails application: - - $ rails new project_manager - -2. Move into the `project_manager` folder and set it up as a git repository: - - $ cd project_manager - $ git init - $ git add --all - $ git commit -m 'Initial import' - -3. Generate scaffolding for a `task` model: - - $ rails generate scaffold task name:string due_date:date description:text project:string completed:boolean - -4. Migrate the database: - - $ rake db:migrate - -5. Restart the server and check you can add tasks at [localhost:3000/tasks](http://localhost:3000/tasks). -6. Add everything to git: - - $ git add --all - $ git commit -m 'Created tasks' - -7. Have a look in `app/controllers` and `app/views/tasks` and see if you can figure out what is going on. -{% endexercise %} diff --git a/_sessions/c4s4/3_mvc.md b/_sessions/c4s4/3_mvc.md deleted file mode 100644 index d5ed0c8..0000000 --- a/_sessions/c4s4/3_mvc.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Model/View/Controller ---- - -Model/View/Controller (MVC) is an application architecture that rails is based on. It works as follows: - -* The Controller deals with incoming web requests. It manages the interaction between the Models and renders the Views. -* The Models correspond to 'business objects'. The Model layer is responsible for storing/retrieving the information in the database (among other things). -* The Views correspond to pages you send to the user. Views are responsible for displaying the data that the Controller has gathered from the Models on the page. - -For a far better expanation please see [this post](http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/). - -### Controllers - -The tasks controller can be found in the file `app/controllers/tasks_controller.rb`. In that file there are several different methods, for example: - -{% highlight ruby %} -# GET /tasks -# GET /tasks.json -def index - @tasks = Task.all -end -{% endhighlight %} - -The comments tell you when this action will run. In the case above, it is when someone makes a `GET` request to `/tasks`. (How requests map to controllers is set up in `config/routes.rb` in this case with the line `resources :tasks`. You can find out more about request routing and `routes.rb` from the [rails routing docs]().) All the `index` action does is to use the `Task` model to pull all the existing tasks out of the database. Just like sinatra it will use the instance variable `@tasks` to share the information with a view. By default the view with the **same name as the action** will be run - in this case `views/tasks/index.html.erb`. - -Scaffolding a model with `rails generate scaffold` will create a controller with the following actions: - -* `index`: for listing all the tasks. -* `show`: for seeing a single task on its own page. -* `new`: for displaying a form to create a task. -* `create`: for receiving the post request from the 'new' form and storing the new task in the database. -* `edit`: for displaying a form to edit a task. -* `update`: for receiving the post request from the 'edit' form and updating the task in the database. -* `destroy`: for destroying the task and removing it from the database. - -These are known as **CRUD** actions, short for 'create', 'read', 'update' and 'destroy', and represent the common actions that are generally performed on models. Rails provides a **RESTful interface** to these actions, by mapping appropriate http requests to the controller through the configuration in `routes.rb`. You can find more out about this in the [rails routing docs]() but, for now, it's not really that important. - -{% exercise %} -1. Read through all the actions in the `tasks_contoller.rb`. -2. One-by-one try them out in your browser (e.g. by clicking on the 'show'/'edit'/'destroy' links on the [localhost:3000/tasks](http://localhost:3000/tasks) page) -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s4/4_views.md b/_sessions/c4s4/4_views.md deleted file mode 100644 index d3657ad..0000000 --- a/_sessions/c4s4/4_views.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Views ---- - -Your app's views can be found in `app/views`. You'll notice that there are view files for most of the controller actions (all the ones that need them): - - - app - + assets - + controllers - + helpers - + mailers - + models - - views - + layouts - + tasks - - _form.html.erb - - edit.html.erb - - show.html.erb - - new.html.erb - - index.html.erb - -(There are also some `.json.jbundle` files. These are new in Rails 4.0. I think they're for making your app accessible as a json api.) The `_form.html.erb` is a *partial* - a view that is shared by other views, which is why it begins with an underscore. `_form.html.erb` is used in both the `edit.html.erb` and `new.html.erb` views. - -### Layouts - -Just like Sinatra, Rails allows you to use layout templates to reduce the amount of repetition in your `erb` files. Rails has even gone so far as to set one up for you. You can have a look at the layout in `app/views/layouts/application.html.erb`. - -`app/views/layouts/application.html.erb` will be used by default by all the views in your application. It is possible to create other layout files (e.g. `admin.html.erb`) to use with certain views. You can find out more about doing this [here](http://stackoverflow.com/questions/14356207/not-rendering-the-default-application-layout-in-rails-3). - -I'm going to add [Twitter Bootstrap]() to the rails app by linking the online version of the css to the top of `application.html.erb`: - -{% highlight html %} - - - - ProjectManager - - !-- Latest compiled and minified CSS --> - - - <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> - <%= javascript_include_tag "application", "data-turbolinks-track" => true %> - <%= csrf_meta_tags %> - - - -<%= yield %> - - - -{% endhighlight %} - -### Where to put CSS and Images - -In Sinatra you had to put CSS and images in the `public` folder. Rails has a different way of dealing with these things: you need to put them in `app/assets/..`. This is to allow Rails to use [sass](http://sass-lang.com/): a special language that makes css easier to write and manage. You might want to investigate sass in the future, for now the important thing is that **writing css in a sass file is fine** - the css will be unchanged and behave as normal. - -Let's write some custom CSS in `app/assets/css/application.css.scss`: - -{% highlight css %} -/* - * This is a manifest file that'll be compiled into application.css, which will include all the files - * listed below. - * - * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. - * - * You're free to add application-wide styles to this file and they'll appear at the top of the - * compiled file, but it's generally better to create a new file per style scope. - * - *= require_self - *= require_tree . - */ - -h1 {color: red;} -{% endhighlight %} - - -{% exercise %} -1. Have a look through all the views in `app/views/tasks`. See if you can work out roughly what they do. -2. Add Twitter Bootstrap to your site (by editing `app/views/layouts/application.html.erb` as above). -3. See if you can change the `index.html.erb` view so that the table is a [Twitter Bootstrap striped table](http://getbootstrap.com/css/#tables-striped). -4. See if you can add a [Twitter Bootstrap navbar](http://getbootstrap.com/components/#navbar) to your site (in `layouts/application.html.erb`). -5. Change the colour of the navbar, by adding some custom css to `app/assets/css/application.css.scss`. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s4/5_the_console.md b/_sessions/c4s4/5_the_console.md deleted file mode 100644 index 0ae01ab..0000000 --- a/_sessions/c4s4/5_the_console.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Rails console ---- - -Rails provides its own special version of `irb` known as the `rails console`. It's basically irb with your rails project already loaded, so that you can easily interact with the application and the database. You start the console at the command line (in your `project_manager` folder): - - $ rails console - -We'll use the console to have a closer look at the `Task` model that was created via the `rails generate scaffold`. - -### Models - -If you take a look at the file `app/models/task.rb` you'll find the following: - -{% highlight ruby %} -class Task < ActiveRecord::Base -end -{% endhighlight %} - -The important bit here is the `< ActiveRecord::Base`, which is saying that the class *inherits* from `ActiveRecord::Base`. `ActiveRecord` is a ruby library that allows you to access SQL, or relational, databases from ruby (whereas `mongoid` was for accessing the NoSQL, or document-based, database MongoDB). You'll note that, unlike `mongoid` we don't specify which fields the `Task` model has - `ActiveRecord` takes this information automatically from the database. `ActiveRecord` is similar to `mongoid` in terms to how you pull things out of the database: - -{% highlight ruby %} -Task.all # to find all the tasks - -# create a new task (not yet in the database) -t = Task.new(:name => "Washing up", :due_date => '14/8/2013', :project => 'Housework') - -# save the task to the database -t.save - -# pull a task out of the database -t2 = Task.first - -# update an attribute -t2.completed = true - -# save the update to the database -t2.save -{% endhighlight %} - -### Adding logic to the model - -A useful question to be able to ask a `Task` would be whether it is overdue yet. It is easy to add this logic to the model in `app/models/task.rb`: - -{% highlight ruby %} -class Task < ActiveRecord::Base - - def overdue? - due_date < Date.today && !completed? - end - -end -{% endhighlight %} - -You can try this out in the rails console (but you need to reload the class to pick up the changes): - - > reload! - > t = Task.last - > t.overdue? - -{% exercise %} -1. Open up `irb` and try working through the set of operations above to experiment with creating a new `Task` and saving it to the database via the rails console. -2. Add the `overdue?` method to the `Task` model. Check you use the new method in `irb`. -{% endexercise %} \ No newline at end of file diff --git a/_sessions/c4s4/6_further_resources.md b/_sessions/c4s4/6_further_resources.md deleted file mode 100644 index 88d95d7..0000000 --- a/_sessions/c4s4/6_further_resources.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Rails resources ---- - -We are not going to do much more Rails in class, but I strongly recommend you use it for your project. I'm hoping that the stuff we've done with Sinatra will have given you enough of insight to be able to effectively discover rails for yourselves. - -One resource that you'll definitely want to have a look at is [Railscasts](http://railscasts.com). For most things you'll want to do in rails there's a railscast telling you how to do it! They're really clear and demonstrate exactly where to put stuff in your rails application. Even if you're not trying to do anything in particular, watching a couple of railscasts is a great way to passively discover more about how rails works. Here are a few you might want to start with: - -* http://railscasts.com/episodes/417-foundation: an overview of a Twitter Bootstrap - like framework called Foundation. -* http://railscasts.com/episodes/310-getting-started-with-rails: advice on how to get started with rails. -* http://railscasts.com/episodes/360-facebook-authentication: how to integrate facebook log-in into your app. -* http://railscasts.com/episodes/209-introducing-devise: how to easily provide a log-in to your site, using [Devise](https://github.com/plataformatec/devise) (this is how you should do authentication!) [Warning: old but probably still relevant]. -* http://railscasts.com/episodes/328-twitter-bootstrap-basics: a ruby gem to make adding Twitter Bootstrap to your app easier. - - -[RailsApps](http://railsapps.github.io/twitter-bootstrap-rails.html) is a great site with many nice tutorials. There's also the [learn rails book](http://learn-rails.com/) which **you can currently get for free**, provided you're willing to give feedback. If you're using this book I'd recommend starting with Chapters 9 and then 14 (and then flicking back and forth as necessary). It's well worth working through - it guides you through a mail list signup and management application, including integration with MailChimp. - -There's also the [Rails Tutorial book](http://ruby.railstutorial.org/ruby-on-rails-tutorial-book) by Michael Hartl, which gives a thorough and up-to-date tutorial for building a rails app. - -Finally, as will all web things, Google is probably your most useful resource for answering most questions! diff --git a/_sessions/c4s4/_1_better_ways.md b/_sessions/c4s4/_1_better_ways.md deleted file mode 100644 index 4c789c1..0000000 --- a/_sessions/c4s4/_1_better_ways.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Better ways ... ---- - -### Jekyll - -### Sass - -### Rails \ No newline at end of file diff --git a/_sessions/c4s4/info.yml b/_sessions/c4s4/info.yml deleted file mode 100644 index 36e9846..0000000 --- a/_sessions/c4s4/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Further Web Programming with Ruby -strapline: Riding the rails \ No newline at end of file diff --git a/_sessions/contents/1_web_fundamentals_1.md b/_sessions/contents/1_web_fundamentals_1.md deleted file mode 100644 index ce1f548..0000000 --- a/_sessions/contents/1_web_fundamentals_1.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Course 1 ---- - -### Web Fundamentals 1 - -* [Session 1: Getting going](/c1s1/) -* [Session 2: Git and CSS](/c1s2/) -* [Session 3: Bootstrapping it up](/c1s3/) -* [Session 4: Analytics and HTML Forms](/c1s4/) - diff --git a/_sessions/contents/2_web_fundamentals_2.md b/_sessions/contents/2_web_fundamentals_2.md deleted file mode 100644 index acc80b7..0000000 --- a/_sessions/contents/2_web_fundamentals_2.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Course 2 ---- - -### Web Fundamentals 2 - -* [Session 1: Collaborative coding](/c2s1/) -* [Session 2: A few extras](/c2s2/) - diff --git a/_sessions/contents/3_introduction_to_ruby.md b/_sessions/contents/3_introduction_to_ruby.md deleted file mode 100644 index 17e9dbc..0000000 --- a/_sessions/contents/3_introduction_to_ruby.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Course 3 ---- - -### Introduction to Ruby - -* [Session 1: The basics](/c3s1/) -* [Session 2: Adding logic](/c3s2/) -* [Session 3: Arrays](/c3s3/) -* [Session 4: Hashes and sending emails](/c3s4/) - diff --git a/_sessions/contents/4_further_ruby.md b/_sessions/contents/4_further_ruby.md deleted file mode 100644 index db35487..0000000 --- a/_sessions/contents/4_further_ruby.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Course 4 ---- - -### Further web programming with Ruby - -* [Session 1: Better logic](/c4s1/) -* [Session 2: Even better logic](/c4s2/) -* [Session 3: Intro to MongoDB](/c4s3/) -* [Session 4: Riding the rails](/c4s4/) - diff --git a/_sessions/contents/info.yml b/_sessions/contents/info.yml deleted file mode 100644 index ac883d6..0000000 --- a/_sessions/contents/info.yml +++ /dev/null @@ -1,2 +0,0 @@ -title: Code61 -strapline: Contents diff --git a/_sessions/extras/0_recap.md b/_sessions/extras/0_recap.md deleted file mode 100644 index cc89d26..0000000 --- a/_sessions/extras/0_recap.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Recap from last time ---- - -### Before you start: updating gitgit - -There have been some updates and improvements to gitgit! To get these -improvements open the command line and run: - - gem update gitgit - -To check it worked run - - gitgit version - -it should say '0.0.5' (or higher). - -### Before you start: verifying github email address - -Today we're going to be putting up your first site using [GitHub -Pages](https://pages.github.com/) - a free hosting solution provided by -GitHub. - -In order for this to work you need to have **verified your email address -with GitHub**. - -{% exercise %} -
        -
      1. Log into GitHub.
      2. -
      3. If you see a warning at the top that you haven't verified your -email address, follow the instructions to do that now.
      4. -
      5. If not, you're good to go!
      6. -
      -{% endexercise %} - -### Review exercise - -{% exercise %} -
        -
      1. Open the comand line
      2. -
      3. Navigate to your 'first_site' folder (cd/ls)
      4. -
      5. Open 'first_site/index.html' in Sublime Text
      6. -
      7. Make a change to the file
      8. -
      9. Save the changes and push to github ("gitgit save", "gitgit -push")
      10. -
      11. Log into github and check you can see your changes
      12. -
      - -{% endexercise %} - -### Something new: publishing site using GitHub pages - -You're now going to publish your 'first_site' using [GitHub Pages](https://pages.github.com/). - -To do this you need to push your website up to a branch called -'gh-pages'. You don't know about branches yet, but you can see them on -github. Right now you'll just see a single branch called 'master'. - -You don't actually need to understand anything about branches at the -moment, as gitgit makes it really easy to publish as a github page. Just -run - - gitgit publish - -When you go to github you should now see a 'gh-pages' option in the -branches dropdown. - -The 'gh-pages' branch is a signal to github that you want your code to -be deployed as a website. You can find the url of your website by -looking in your repository settings on GitHub. diff --git a/_sessions/extras/2_domain_name.md b/_sessions/extras/2_domain_name.md deleted file mode 100644 index 386d28a..0000000 --- a/_sessions/extras/2_domain_name.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Wiring up your domain ---- - -### Getting your domain name to point to your GitHub Page - -The point of this exercise is to set up your domain name to point towards your new GitHub pages site. - -As GitHub hosts many different pages at their IP address, it isn't quite as simple as pointing your domain address towards that IP address. There are two things you need to do to get your domain name working with your GitHub pages site: - -1. Tell your domain registrar (e.g 123-reg or godaddy) to point your domain name towards GitHub's IP address. -2. Tell GitHub that requests to your domain name should come to your site. - -Github explains this [here](https://help.github.com/articles/setting-up-a-custom-domain-with-pages). - -### Pointing your domain name towards GitHub - -For the first bit you need to log in to your domain registrar and change the DNS settings. You want an *A-record* pointing to `204.232.175.78` (which is github.com). Note that it can take up to a couple of days for DNS changes to propagate. - -If you're using 123-reg, your should log in, select your domain from the list, and click "Manage". You should then go to "Manage DNS". - -![123-reg DNS Settings](/assets/dns_settings.png) - -(The @ dns entry stands for the root or bare domain.) - -{% exercise %} -Log in to your domain registrar and set an A-record to point towards GitHub. -{% endexercise %} - -Your changes won't take effect immediately. - -### Tell github to expect requests for your domain name - -{% exercise %} -1. Open Sublime Text and create a new file. -2. Write your domain name on the first line of the new file e.g: - - mydomain.com - -3. Save that file as `CNAME` (uppercase, with no extension) in your `first_site` folder -4. Commit your change and then push to github. -{% endexercise %} diff --git a/_sessions/extras/3_github_account.md b/_sessions/extras/3_github_account.md deleted file mode 100644 index c9a7605..0000000 --- a/_sessions/extras/3_github_account.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: GitHub account ---- - -Git is a program that helps with the management of code. It means that you completely avoid the situation where you end up with files called `team_contacts_v1`, `team_contacts_v2` etc. It also allows you to share your code with others and collaborate on code in an efficient way. - -GitHub is a site that makes sharing code part of git really easy. It is the go-to choice both for startups and open-source software projects. (There are several other sites that are similar to GitHub e.g. [BitBucket](https://bitbucket.org), but GitHub is the most widely used.) - -GitHub also allows you to put a static website online for free, using [GitHub Pages](http://pages.github.com/). We will be making use of this feature during the course. - -{% exercise %} -Sign up for a GitHub account at [https://github.com/](https://github.com/). Make sure you **know your password** to avoid awkward moments in class! -{% endexercise %} diff --git a/_sessions/extras/4_command_line.md b/_sessions/extras/4_command_line.md deleted file mode 100644 index 46d05cd..0000000 --- a/_sessions/extras/4_command_line.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Meet the Command Line ---- - -The command line is a way to interact with your computer programmatically. If you are doing any software development you will need to get to grips with using the command line, as many of the programs you will use will be run from the it, instead of by clicking an icon. - -### Opening the command line - -* On a Mac open Terminal (Applications > Terminal) -* On Windowns open Command Prompt with Ruby on Rails - - -### Moving around - -Note: when giving you instructions for the command line we will precede them with a `$` to represent the command prompt e.g. - - $ some_command - -**You shouldn't type the `$` sign - just the stuff after it.** So for the above instruction you would just type `some_command` into the command line. - - -The first thing you will need to get used to is moving around. Start by printing the name of the directory you are in: - - $ pwd - -Then have a look at what's in that directory ( _list_ the contents): - - $ ls - -To move up a directory ( _change directory_ ) do - - $ cd .. - -To move back into the folder you just left do - - $ cd name_of_the_folder - -Your commandline will help you: tab can often be used to auto-complete names of files, the up arrow can be used to cycle through previous commands that you have typed. - -### Creating a directory - -You can do a lot more on the command line than just move around. We'll be using the command line a lot over the course. For the time being we just need to create a folder: - - $ mkdir coding_course - -Note: choosing names without spaces makes command line navigation easier. - -{% exercise %} -1. Open your command line: - * On a Mac open Terminal (Applications > Terminal) - * On Windowns open Command Prompt with Ruby on Rails -2. Find out where you are: - - $ pwd - -3. See what is in the same folder: - - $ ls - -4. If you are on a Mac move into `Documents`: - - $ cd Documents - -5. Create the folder for the coding course: - - $ mkdir coding_course - -6. Move into that folder: - - $ cd coding_course - -7. Move back up to the folder above - - $ cd .. - -8. Move back into the coding course folder. This time don't type out coding_course - just type out the first few letters and hit `Tab`: - - $ cd coding_course - -9. In the Finder (Mac) or My Computer (Windows) find the folder that you just created. -{% endexercise %} diff --git a/_sessions/extras/4_ruby_git.md b/_sessions/extras/4_ruby_git.md deleted file mode 100644 index 335276a..0000000 --- a/_sessions/extras/4_ruby_git.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: Ruby and Git ---- - -In order to save to github you'll need a program called git on your -laptop. To make git easier we'll be using a program called gitgit. -To run gitgit you need ruby installed, so in this step we'll install -that too. - -### On Windows - -On Windows the guys at [Rails Installer](http://railsinstaller.org/en) have put together a single package that contains both ruby and git. We're going to use that to get both on your laptop. - -{% exercise %} -If you are on Windows: -* Download and install [Rails Installer](http://railsinstaller.org/en) -{% endexercise %} - -### On a Mac - -Macs come with ruby already installed, so you don't have to worry about -getting ruby! - -To install git we're going to use a tool called [Homebrew](http://brew.sh/), which helps install open source software to a mac. - -{% exercise %} -* Open `Terminal` (Applications > Utilities > Terminal). -* Follow the installation instructions on the [Homebrew site](http://brew.sh/). It will ask you to copy and paste something like - -
      
      -ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
      -
      - -into the Terminal. (You should check this, as the precise - instructions might have changed.) - -* Once homebrew in installed type the following into the Terminal: - - brew install git -{% endexercise %} diff --git a/_sessions/extras/5_push_to_github.md b/_sessions/extras/5_push_to_github.md deleted file mode 100644 index d410380..0000000 --- a/_sessions/extras/5_push_to_github.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: "Pushing to GitHub" ---- - -Git is a version control system. It allows you to keep the entire history of your code, and makes it easy to share and collaborate with others. - -### Using git - -Using git is really easy: - -1. Set up a folder to be a _git repo_. This tells git to track all changes in that folder. -2. After you've made some changes, save them into the repository. -3. Once you've saved the changes push them up to github. - -The first point is important: *git works on a folder level*. It tracks all the changes you make to files within a given folder. - -### Actually using git - -Actually using git is a bit harder. It's a very powerful tool and pretty complex to get started with. To make things simpler, we're going to use a tool called `gitgit`. - -To install gitgit open the command line and type the following: - - gem install gitgit - -To see if this worked, type - - gitgit - -You should see a list of gitgit commands something like this: - - $ gitgit - Commands: - gitgit help [COMMAND] # Describe available commands or one specific command - gitgit init # Initialise a git repo - gitgit lg # Show your recent saves - gitgit push # Push your changes to github - gitgit save # Save you changes to the repo - gitgit status # See what changes you've made since you last save - -If it didn't work, you might need to do - - sudo gem install gitgit - -and type your password. - -You also might need to do - - rbenv rehash - -If in doubt contact a teaching assistant! - -### Using gitgit - -To **make a folder into a git repository**: - - gitgit init - -then follow the instructions. You'll only need to do this once for each folder you want to make into a repository. - -After you've made some changes to your files and saved them, you can **save them into your repo** by typing: - - gitgit save - -Finally, to push your code up to github you can do - - gitgit push - -Before you do this, you will need to setup your repo with github. - -### Setting up your repo with github - -Go to github, login, and click "Create New Repo" in the top left hand corner. - -![Creating a repo on GitHub](/assets/create_repo.png) - -Follow the instructions, calling it something like `first_site`. **Do not** click the box which says 'Create a readme with this repository'. You'll get to a page when it'll describe how to get your code online. You want to follow the instructions for "Pushing an existing repository to github". - -### Pushing your code to github - -We will now set up your `first_site` folder to use git and push it up to github. - -{% exercise %} -
        -
      1. Navigate to your first_site folder using cd and ls.
      2. -
      3. Make it into a git repo: "gitgit init"
      4. -
      5. Save all the work you've done so far: "gitgit save"
      6. -
      7. Log in to GitHub.
      8. -
      9. On github create a new repository called 'first_site'. DO NOT click the box which says 'Create a readme'.
      10. -
      11. Copy and paste the instructions it gives you into the command line. You are 'Pushing an existing repository to github'.
      12. -
      13. Go back to github and refresh the page. You should see your code.
      14. -
      -{% endexercise %} diff --git a/_sessions/extras/9_configuration_variables.md b/_sessions/extras/9_configuration_variables.md deleted file mode 100644 index 8ec9ef0..0000000 --- a/_sessions/extras/9_configuration_variables.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Configuration variables ---- - -The purpose of this next part is to add an email notification to the sign-up form you worked on last time. - -### Problem: where to store the password - -In the example email script you were prompted for your gmail username and password. This meant we side-stepped the issue of where to write this (sensitive) information down. - -The problem of where in your program to store sensitive, application-specific configuration data is one that you will come across often. For example, you may want to store: - -* An email username/password for your app. -* Database configuration, username and passwords. -* Amazon webservices api tokens and secret key (e.g. Amazon S3 etc.). -* Facebook integration token and key. -* GitHub integration token and key. -* ... tokens and keys to connect to many other services. - -Quite often these keys will have different values in different *environments*: you probably won't want to use your live production database when developing or testing. - -A tempting (but non-ideal) place to put this information is in the code in your git repository (i.e. just write them into the source code files). This is bad for a few reasons including: - -1. Anyone with access to your git repository has access to your email password etc. -2. It's hard to manage different versions for different environment - you will need to remember to replace your development info with your production info everytime before you do a 'git push heroku'. - -In general **it is bad practice to put passwords/tokens/keys in your git repo**. - -### Using ENV variables - -A good solution for this situation is to use environment variables. All ruby programs have access to an `ENV` hash containing options from the environment where the program is run. You can see the environment variables set on your computer by running - - $ env - TERM_PROGRAM=Apple_Terminal - SHELL=/bin/bash - TERM=xterm-256color - ... - -You can then check that you can access these in irb: - -{% highlight ruby %} -> ENV['SHELL'] -#=> "/bin/bash" -{% endhighlight %} - -We are going to store the configuration values (e.g. email username and password) as environment variables for our program. Heroku makes it easy for you to manage ENV variables on their servers, as described [here](https://devcenter.heroku.com/articles/config-vars). To replicate the situation on your laptop you can use a gem called `dotenv`. - -You can install `dotenv` via rubygems. If you use `rbenv` (i.e. if you followed 'The Hard Way' installation instructions) you will then need to do a `rbenv rehash`. (This is because the foreman gem comes with a command line tool, which we need to tell rbenv about.) - - gem install dotenv - - -{% highlight ruby %} -# in .env -GMAIL_USER_NAME=yourgmailusername -GMAIL_PASSWORD=password12345 -{% endhighlight %} - -You can then access these variables in your ruby program by the `ENV` hash: - -{% highlight ruby %} -user_name = ENV['GMAIL_USER_NAME'] -password = ENV['GMAIL_PASSWORD'] -{% endhighlight %} - -In order to keep your `.env` configuration secret you need to make sure it doesn't get added to the git repo. If you want to deploy to Heroku, it is also important that your `Procfile` **isn't** in your git repo (otherwise it will mess with Heroku's settings when it gets up there). To do this you need to make sure both of them are in your `.gitignore`: - -{% highlight ruby %} -# in .gitignore -Procfile -.env -{% endhighlight %} - -{% exercise %} -1. Fetch down the changes to `mongo1`. In the `mongo1` directory: - - $ git fetch - -2. Checkout the `email` branch: - - $ git checkout email - - This has the solution from last time along with some email examples. If you spent a lot of time making your solution from last session look nice, you might instead want to merge the `email` branch into your `master` - up to you! -3. Do a `bundle install` (and a `rbenv rehash` if necessary): - - $ bundle install - $ rbenv rehash - -3. Copy the contents of `mongo1/example_app/Procfile.sample` and `mongo1/example_app/.env.sample` and save them as `mongo1/example_app/Procfile` and `mongo1/example_app/.env` filling in your gmail details in `.env`. -4. Start the app with `foreman start`. Check that the app sends you a fruity email. -{% endexercise %} - - -### ENV variables on heroku - -As the settings in `.env` aren't in the git repo, they won't be pushed to heroku. You will need to set these variables separately. Heroku makes it easy to do this. Assuming your app is already on heroku you can set environment variables as: - - $ heroku config:set GMAIL_USER_NAME=yourgmailusername - $ heroku config:set GMAIL_PASSWORD=password12345 - -You can check the values you have set by running - - $ heroku config - -There are other tools you can use to manage heroku configuration variables, which might be useful if you end up setting a lot of options. See [here](https://github.com/ddollar/heroku-config) for more details. \ No newline at end of file diff --git a/_sessions/extras/info.yml b/_sessions/extras/info.yml deleted file mode 100644 index a3f1688..0000000 --- a/_sessions/extras/info.yml +++ /dev/null @@ -1 +0,0 @@ -title: Extras \ No newline at end of file diff --git a/c1prep/index.html b/c1prep/index.html new file mode 100644 index 0000000..c583970 --- /dev/null +++ b/c1prep/index.html @@ -0,0 +1,179 @@ + + + + + + Course Preparation + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Welcome

      + +

      Welcome to the course preparation for the Introduction to Web Programming course!

      + +

      The course will cover a basic introduction to web progamming, starting from scratch. You will develop your understanding of how the internet works, learn to code a basic site using HTML and CSS, and learn how to manage your code and get your site online using a tool called git. This course is a pre-requisite for all other courses offered by The Oxford Codelab.

      + +

      There are many excellent resources on the web for learning a lot of this material. We don’t want to reinvent the wheel and will unashamedly point you towards better sources of information when they exist. Rather than teach you everything from scratch, we aim to guide and support your learning.

      + +

      Installing software

      + +

      One of the biggest challenges in a course like this is dealing with the different operating systems and hardware that you’ll be working on. We have decided against getting everyone to run a linux virtual machine (or similar) for the course, as it’s really important that web development is something that you can do in your natural computing environment.

      + +

      That does mean that there’s a bit of setting up that you will need to do to be ready for the first session next week. Please be patient with this - installing software is fiddly and not always predictable. Most of the work we get you to do won’t be like this!

      + +

      The tabs on the left hand side will take you through installing the software you’ll need for the course. Instructions are given in blue boxes.

      +
      Task: + +

      The blue boxes tell you what you need to do!

      + +
      +

      If you have any problems, please contact the tech team!

      + +
      + + +
      + + +

      Google Chrome

      +
      Task: + +

      Download and install Google Chrome.

      + +
      +

      Why do I need Chrome?

      + +

      Chrome is a free web browser provided by Google. There are several other web browsers that you might have used, including Internet Explorer, Safari, Firefox and Opera. We will be using Chrome as it comes with a good set of developer tools that we will be using over the course.

      + +

      Firefox also comes with an excellent set of developer tools (via its firebug extension). There doesn’t seem to be much between Chrome and Firefox+firebug as far as the tools we’ll be using go. The decision to recommend Chrome was fairly arbitrary, but means that everyone will be using the same software.

      + +
      + + +
      + + +

      Sublime Text

      +
      Task: + +

      Download and install the appropriate version of Sublime Text for your computer from http://www.sublimetext.com/.

      + +
      +

      Why do I need Sublime Text?

      + +

      Sublime Text is a text editor - a program that can be used for writing code.

      + +

      When you write code it is important that the editor stores just the text you wrote, so that it can be properly interpreted when you run it. Word processors, like MS Word, add a lot of extra information to the text you write - layout, font styles, etc. - so can’t be used for this purpose.

      + +

      You probably already have a text editor, such as notepad or textedit, on your laptop that could be used for writing code. Sublime Text is better because it also does syntax highlighting - it will colour your code, making it easier to see what’s going on.

      + +

      Do I need to pay?

      + +

      Sublime Text costs $70 but you can use it for free as it has an indefinite evaluation period. The duration of the course seems like a pretty reasonable period of time to evaluate the software. If you go on to use it after that you should consider getting a license - it’s a good product and the guys who make it have to eat!

      + +

      Why Sublime Text?

      + +

      There are many text editors available including many excellent free and/or open source ones. Sublime Text is a popular code editor in the web development world at the moment and benefits from an active community of developers contributing add-ons and improvements. Although it isn’t free or open source, we have chosen it as our recommended editor as it: (a) gives a good user experience on mac, linux and windows; (b) is easy to get started with; and (c) can be easily customised when you get more advanced.

      + +

      If have a different text editor that you are already used to using, feel free to use that instead!

      + +
      + + +
      + + +

      Preparation exercises

      + +

      Well done for getting to this point! You should now have all the software you need to start the course.

      + +

      In the first session we will be looking at HTML and the overall structure of the internet. We won’t be spending much time on these, so it will help if you’ve at least seen then before. To help everyone has a basic amount of knowledge to start, please do the following:

      +
      Task: +
        +
      1. Watch these two videos about the DNS system: video1 (excuse the political overtones), video2
      2. + +
      3. Sign up to General Assembly Dash and complete the whole of Project 1. (Will probably take about 30mins).
      4. + +
      5. (Optional) Sign up to Codecademy. On the Codecademy web track: +
          +
        1. Do the project from "1 Introduction to HTML".
        2. + +
        3. Do the project from "2 HTML Structure: Using Lists".
        4. + +
        5. Do the project from "3 HTML Structure: Tables, Divs, and Spans".
        6. +
        +
      6. +
      +
      +

      Look forward to seeing you at the first session!

      + +
      + +
      + +
      + + + + +
      + + + + diff --git a/c1prep_linux/index.html b/c1prep_linux/index.html new file mode 100644 index 0000000..6ca4b4f --- /dev/null +++ b/c1prep_linux/index.html @@ -0,0 +1,69 @@ + + + + + + c1prep_linux + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      + +
      + +
      + +
      + + + + +
      + + + + diff --git a/c1s1/index.html b/c1s1/index.html new file mode 100644 index 0000000..96d3cf1 --- /dev/null +++ b/c1s1/index.html @@ -0,0 +1,561 @@ + + + + + + Web Fundamentals 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Course Overview

      + +

      Who is this course for?

      + +
        +
      • You want to start a start-up and be your own technical cofounder
      • + +
      • You want to have your own blog and understand how it works
      • + +
      • You want to have the foundations to teach yourself more
      • +
      + +

       What will we learn

      + +
        +
      • How to inspect and learn from other sites
      • + +
      • How to put up a webpage
      • + +
      • Basic skills and tools that will be useful for any coding you do
      • +
      + +

      Hope you will become curious about how the internet works and will look at websites in a different way.

      + +

      It’s worth pointing out that this is not the easiest way to put up a website. There are many site builders/blogging platforms which will allow you to put up a website quickly and easily in a point-and-click manner (eg. weebly or wordpress). The focus of this course is learning the basics of how and why things work and to provide the basis to build upon in future courses.

      + +

       How to study

      + +

      The hardest thing about learning to program is knowing where to start and what to learn. The course aims to provide a basic overview of the technologies used, along with the tools and resources to discover more. We do not aim to cover anything in great depth or comprehensive detail.

      + +

      The lectures will be as hands-on and practical as possible. Each week there will be a number of tasks to do in between the sessions to reinforce what you have learnt. It’s up to you whether you do the tasks or not, but the more you put in the more you will get out!

      + +
      + + +
      + + +

      What is a web page?

      + +

      A webpage is just a set of files that your web browser knows how to display.

      + +

      There are three possibilities for the types of files they could be: HTML, CSS and Javascript. Most web pages will be a mixture of all three. Because the files have to be able to be interpreted by all web browsers on all operating systems, the choices are limited and don’t change very often.

      +
        +
      • +
        + +

        HTML

        +

        HyperText Markup Language encodes the information that is sent back from the server.

        +
        +
      • +
      • +
        + +

        CSS

        +

        Cascading Style Sheets tell your browser how to display that information.

        +
        +
      • +
      • +
        + +

        Javascript

        +

        Javascript is a programming language that can be used to provide client-side interactivity.

        +
        +
      • +
      +

      HTML, CSS and Javascript are known as client-side technologies, because they are sent to your web browser (the client).

      + +

      Programming language vs markup language

      + +

      HTML (HyperText Markup Language) is a way of writing information so that it can be interpreted by a web browser. It is not a programming language - you can’t do calculations in it - it is a markup language. CSS is also a markup language. Javascript is a programming language.

      + +

      Content/style separation

      + +

      Back in the early days of the web HTML would both store the information and tell the browser how to display it. People then realised that this was a bad idea - making a small change such as changing the colour of a heading would require edits all over the place, which made sites hard to maintain. HTML is now used just to display the information (text etc.) that is stored in the page. CSS is used to tell the browser how to display the information.

      + +

      Viewing HTML, CSS and js

      + +

      Because the HTML, CSS and js are sent to your browser, it is easy for you to look at them. There are no secrets in HTML, CSS or js. If there’s a part of a webpage that you like, it’s easy to find out how it is coded and use the technique yourself.

      + +

      Every browser provides a way to look at the source of the page you’re currently viewing. In Chrome you do View > Developer > View Source. This will show you the raw HTML but isn’t always the easiest thing to look at.

      + +

      Several browsers also provide developer tools, which allow you to interactively view the page source. In Chrome you can access these by doing View > Developer > Developer Tools. If you use Firefox, you can get similar functionality with the Firebug plugin. These tools are the best way to investigate a web page. Over the course you will be using them a lot on your own pages, especially when things aren’t working exactly as you expect.

      + +

      There are a few features of the Chrome developer tools that it is worth pointing out now.

      +
      Task: +
        +
      1. Open this page in Google Chrome
      2. + +
      3. View the page source by doing one of the following: +
          +
        • View > Developer > View Source
        • + +
        • Tools > View Source
        • +
        +
      4. + +
      5. Open the developer tools by doing one of the following: +
          +
        • View > Developer > Developer Tools
        • + +
        • Tools > Developer Tools
        • +
        +
      6. + +
      7. Use the magnifying glass in the bottom left to hover over bits of the page and find the related HTML.
      8. + +
      9. Hover over the HTML code in the developer tools box and watch as different parts of the page are highlighted.
      10. + +
      11. Try changing some of the CSS on the right hand side. To undo any changes just refresh the page.
      12. + +
      13. Have a look on the Resources tab. See if you can find the CSS, javascript and image files used on this page.
      14. + +
      15. Visit a few of your favourite websites and repeat this process.
      16. +
      +
      +
      + + +
      + + +

      Web servers

      + +

      You can think of the internet as a massive network of computers that can send files to one another. The computers that hold web pages are called servers. Servers are large, specialised computers that are permanently connected to the internet.

      + +

      Once the address of the web server has been found your request is forwarded on to it, the web server will interpret your request and send back one or more files. We now look at the technology involved in this process.

      + +

      Static vs dynamic sites

      + +

      There are two main possibilities server-side: either your site is static or dynamic.

      + +
        +
      • In a static site all the pages are pre-prepared and the web server just sends them to the browser.
      • + +
      • In a dynamic site the pages are prepared on-the-fly pulling information out of a database depending on what the user asked for.
      • +
      + +

      Most of the sites you can think of will be dynamic sites (e.g. [facebook.com], [reddit.com], [amazon.com], ..).

      + +

      Server-side technologies

      + +

      There are many options for building a dynamic server-side site - you’re pretty much free to do what you like. Some common choices are:

      +
        +
      • +
        + +

        Ruby on Rails

        +

        A web development framework written in the Ruby programming language.

        +
        +
      • +
      • +
        + +

        php

        +

        A programming language that formed the basis of most dynamic websites in the early 2000s.

        +
        +
      • +
      • +
        + +

        django

        +

        A web development framework written in the Python programming language.

        +
        +
      • +
      • +
        + +

        Node.js

        +

        A web development framework written in javascript.

        +
        +
      • +
      • +
        + +

        Wordpress

        +

        A blogging platform (now capable of much more) written in php.

        +
        +
      • +
      +
      + + +
      + + +

      Introducing the URL

      + +

      Many of our web interactions begin with a URL (uniform resource locator) being typed into our web browser address bar. Let’s look at an example: http://www.bbc.co.uk/news/.

      + +

      This URL has several different parts to it:

      + +
        +
      • http : the protocol or how to fetch the information
      • + +
      • www.bbc.co.uk : the host or where to fetch it from
      • + +
      • /news : the path or precisely what information to fetch
      • +
      + +

      When we type the URL into the address bar a request is sent over the internet and some information is returned to us.

      + +

      The protocol describes how the information is transmitted. Other possibilities include https for secured communication, ftp for file transfer and git which you’ll learn about later.

      + +

      The host describes where the information should come from and the path tells that location precisely what information to send.

      + +

      In general a URL can be more complicated than this. URLs can also contain query parameters, fragments and port information. We will leave these for now but will point them out when we meet them later. Instead we will focus on exactly what information is being sent and who is sending it.

      + +

      Each computer on the internet has an address (an IP address) so that requests can be sent to it and files returned - much like a telephone number. The backbone of the internet is a network of routers that are responsible for routing files from one IP address to another.

      + +

      DNS

      + +

      IP addresses are a sequence of numbers and ‘.’s such as 212.58.244.67. These aren’t very easy to remember. Instead the internet works on a domain name system, that matches domain names such as bbc.co.uk to IP addresses.

      +
      Task: + +

      Type 212.58.244.67 into your browser's address bar. What happens?

      + +
      +

      One of the first things that happens when you type a URL into your browser is a DNS lookup: your computer contacts a DNS server (Domain Name System server), which is basically a massive address book of IP addresses. The DNS server converts the domain name from the URL (e.g. bbc.co.uk) into an address for a server (such as 212.57.244.67).

      + +

      Putting up a website

      + +

      If you want to put up your own website at your own domain name you need two things:

      + +
        +
      1. A web server to serve your site
      2. + +
      3. A domain name to point towards it
      4. +
      + +

      There are many options for web servers - you don’t have to physically have your own one. There are many companies that will offer web hosting, often providing you with space on a shared server. Later in the course we will use the free hosting offered by GitHub through GitHub Pages.

      + +

      To buy a domain name you need to use a domain registrar. Examples include 123-reg.co.uk, godaddy.com and namecheap.com. You pay the registrar to contact the body who manages a TLD (e.g. .com, .org., .co.uk) and put your server’s IP address in their DNS address book. If someone else already owns the domain you might be able to buy it off them, but this can be expensive!

      + +

      Many domain registrars will try to sell you hosting and other site building tools when you buy a domain. It’s important to remember that the domain name is completely separate from the hosting and you don’t need to do them both through the same company - don’t buy anything you’re not going to use.

      + +
      + + +
      + + +

      Creating an HTML page

      + +

      One of the nice things about HTML is you don’t need any fancy software to test it out on your laptop: all you need is a text editor and a web browser.

      +
      Task: +
        +
      1. Inside your coding_course folder create another folder called first_site.
      2. + +
      3. Open Sublime Text.
      4. + +
      5. Write "Hello"
      6. + +
      7. Save the file as index.html in the first_site folder
      8. + +
      9. Open index.html in Chrome. Depending on your version of Chrome +
          +
        • File > Open
        • + +
        • Cmd-o (Mac) or Ctrl-o (Windows)
        • +
        +
      10. +
      +
      +

      Why index.html?

      + +

      In the old days of the web, navigating a website was a lot more like moving around the folder system on your laptop. You would go to a base site and there would just be a list of the files and folders available: an index. Because of this index.html is still the default file that a server will serve when you navigate to a folder in the web browser.

      +
      Task: +
        +
      1. Go back to 'index.html' in Sublime Text.
      2. + +
      3. Change the text to
      4. +
      +
      <h1>Hello</h1>
      +
      + + +
        +
      1. Go back to 'index.html' in Chrome and refresh the page (Cmd-R)
      2. +
      + +
      +

      This is your first line of HTML. It has an open tag and a close tag. They tell your browser to display the text in-between as a heading.

      + +
      + + +
      + + +

      More HTML

      + +

      Now we will look at some slightly more interesting things you can do with HTML.

      + +

      HTML file layout

      +
      <!DOCTYPE html>
      +<html>
      +    <head>
      +        <title>Page title</title>
      +    </head>
      +    <body>
      +        ...
      +    </body>
      +</html>
      +
      +
        +
      • The doctype tells you what sort of html you’re using (html5, html4 …). With html5 it’s simple - you just write html.
      • + +
      • Everything is wrapped in an <html> ... </html> tag
      • + +
      • Things within the <head> .. </head> are used to provide information about the page
      • + +
      • Only things within the <body> ... </body> tags are displayed on the page
      • + +
      • … for example the text within <title> ... </title> will be displayed in the browser bar
      • +
      + +

      Headings

      +
      <h1>Top level heading</h1>
      +
      +<h3>Lower level heading</h3>
      +
      +
        +
      • There are six levels of heading h1h6
      • + +
      • The higher numbers are more important
      • + +
      • It’s usual to only have one h1 on a page
      • + +
      • You rarely see anything below h4 in real pages
      • +
      + +

      Paragraphs and text

      +
      <p>This is a paragraph.</p>
      +
      +<p>This is another paragraph. It has some <em>italic text</em> and some <strong>bold text</strong>.</p>
      +
      +
        +
      • Paragraphs are created using the <p> tag
      • + +
      • The <em> tag is used to provide emphasis. In reality that means italics - in fact the tag <i> also works. Using em is better though as it fits with the idea of semantic markup - marking your information as to its meaning, instead of how you want it to look.
      • + +
      • The <strong> tag is used to make text stand out. It basically means bold - <b> also works, but <strong> is better - see above.
      • +
      + +

      Comments

      +
      <!-- comments look like this -->
      +
      +
        +
      • Comments will not display in the page
      • + +
      • … but they will display in the page source. Don’t be rude!
      • +
      + +

      Lists

      +
      <ul>
      +    <li>Apples</li>
      +    <li>Oranges</li>
      +</ul>
      +
      +
        +
      • Lists have a nested structure
      • + +
      • <ul> is for an unordered list. This means bullet points.
      • + +
      • <ol> is for an ordered list. That means automatic numbering.
      • + +
      • In both types of list you add items using a <li> tag. This stands for list item.
      • +
      + + +
      <a href="http://www.facebook.com">this is a link to facebook</a>
      +
      +
        +
      • The href property tells you where the link will point
      • + +
      • You can specify this link in different ways: +
          +
        • absolute external link e.g. “http://www.facebook.com”
        • + +
        • absolute local link e.g. “/about”. This links to a file relative to the root of your webserver. For example if your site is at www.example.com the link will point to www.example.com/about
        • + +
        • relative local link e.g. “about”. This links to a file relative to the current html document. In this case it will link to the file called about in the same folder as your current html file.
        • +
        +
      • + +
      • You can also link to places in the same document using href="#my_tag". More on this later.
      • + +
      • You can get the link to open in a new tab like this: <a href="http://www.facebook.com" target="_blank">
      • +
      + +

      Images

      +
      <img alt='my cat' src="my_cat.png">
      +
      +
        +
      • The alt tag is for providing a description of your image. This is useful for partially sighted people using screen readers, or in case the image doesn’t load.
      • + +
      • The file can be linked to in the same way as href. In the example above we use a relative local link to a file called my_cat.png in the same folder as the html file.
      • +
      + +

      Tables

      +
      <table>
      +    <thead>
      +        <tr>
      +            <th>Column1 Heading</th>
      +            <th>Column2 Heading</th>
      +        </tr>
      +    </thead>
      +    <tbody>
      +        <tr>
      +            <td>Row1, Column1</td>
      +            <td>Row1, Column2</td>
      +        </tr>
      +        <tr>
      +            <td>Row2, Column1</td>
      +            <td>Row2, Column2</td>
      +        </tr>
      +        <tr>
      +            <td>Row3, Column1</td>
      +            <td>Row3, Column2</td>
      +        </tr>
      +    </tbody>
      +</table>
      +
      +

      Now you will use these ideas to create a richer web page.

      +
      Task: +
        +
      1. Create a folder called coding_course to hold all your work for the course.
      2. + +
      3. Go to the github repository for this session: https://github.com/code61/learning_html
      4. + +
      5. Download the code into your coding_course folder (by clicking 'Download ZIP' in the bottom right).
      6. + +
      7. Open the whole folder in Sublime Text
      8. + +
      9. Open the file example.html in Chrome and look around with the developer tools
      10. + +
      11. Open the file notes.html in Sublime Text.
      12. + +
      13. Change notes.html into valid html so that it looks like notes_solution.jpg
      14. +
      +
      +
      + + +
      + + +

      Homework

      + +

      Finishing off

      +
      Task: + +

      Finish the HTML exercise from the last section.

      + +
      +

      Preparation for next time

      +
      Task: +
        +
      1. Complete the whole of Project 2 on the General Assembly Dash site.
      2. + +
      3. (Optional) Do the projects from the Codecademy Web Track Sections 4, 5 & 6.
      4. +
      +
      +

      Make a start on your own site

      +
      Task: + +

      Use what you've learnt from the HTML exercise and the Dash projects to improve your first_site/index.html. Maybe add some content about yourself. Don't worry if it doesn't look great yet - we'll be working on it more in the next few weeks. Just make sure it says something more than 'Hello'!

      + +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c1s2/index.html b/c1s2/index.html new file mode 100644 index 0000000..c91434e --- /dev/null +++ b/c1s2/index.html @@ -0,0 +1,419 @@ + + + + + + Web Fundamentals 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Recap from last time

      + +

      HTML/CSS

      + +
        +
      • Webpage is just a collection of files: HTML, CSS & Javascript.
      • + +
      • We can edit these files locally.
      • + +
      • We can create them locally (using a text editor) and view then in a browser.
      • +
      + +

      Putting your site online

      + +

      We’re going to use BitBalloon to host our site - BitBalloon will provide the server where the files for our site is stored.

      +
      Task: +
        +
      1. Create an account on BitBalloon.
      2. + +
      3. Upload your site by dragging and dropping your first_site folder onto the BitBalloon website.
      4. + +
      5. Visit your site online!
      6. +
      +
      +

      Your site will currently show up with a url something like teller-balances-48402.bitballoon.com. Part of your homework will be to buy your own domain name to point towards BitBalloon. (You will need to upgrade to the $5/month BitBalloon account to make this possible.)

      + +

      Preparation

      +
      Task: +
        +
      1. Go to the github repository for this session: https://github.com/code61/html2
      2. + +
      3. Download the code into your coding_course folder (by clicking 'Download ZIP' in the bottom right).
      4. +
      +
      +
      + + +
      + + +

      CSS

      + +

      Last time we looked at HTML, and saw how this was used to mark up the information in a webpage. Right now, your HTML pages don’t look very good, as you haven’t given any styling information. The way to do this is using CSS (Cascading Style Sheets).

      + +

      CSS is a way of separating the way your page looks from the content that it displays. As an extreme example of this check out CSS Zen Garden - by clicking on the links you completely change how the site looks, but the html remains unchanged.

      + +

      There are a few ways to include CSS in an HTML file:

      + +
        +
      1. Put the css inline in the html.
      2. + +
      3. Put the css in a <style>..</style> section in the <head>
      4. + +
      5. Link to a separate .css file in the <head>
      6. +
      + +

      The first way is sometimes useful, but defeats the point of using CSS to separate presentation and information. The second way is a bit better and is what we’ll do now - it’s nice to have everything in a single file when you’re just starting. The third way is the best. We’ll look at how to do this next time.

      + +

      CSS in the <head>

      + +

      If you’re putting your CSS in the <head> of your html file (option 2) it should look something like this:

      +
      <head>
      +  <title>Some title</title>
      +  <style>
      +    h1 { color: red; }
      +  </style>
      +</head>
      +
      +

      The bit inside the <style> tags is CSS. The h1 bit specifies the tag that will be styled. The bit inside the { ... } specifies the styles that will be applied. Here we change the colour of the h1 text red.

      + +

      If you save the changes to the html file, then open (or refresh) the page in your browser you should see the changes. By opening the developer tools, and hovering over the h1 you should be able to see your css rule at the side.

      + +

      A few more properties

      + +

      In the example above we changed the color of the h1 element. Here are a few examples of other simple properties you can try out while you’re getting the hang of css:

      +
      p { font-family: 'Arial'; }
      +h2 { font-size: 20px; }
      +h3 {
      +    background-color: green;
      +    font-size: 2px;
      +}
      +
      +

      Note that you can specify multiple properties on one element. When you do this it’s nice to lay them out on multiple lines as done above.

      +
      Task: +
        +
      1. Open `exercise1.html` in Sublime Text and in Chrome.
      2. +
      3. Add some css in the `head` to make the `h1` turn red.
      4. +
      5. Continue with the exercise until `exercise1.html` looks like `exercise1_solution.png`.
      6. +
      +
      +
      + + +
      + + +

      Selectors and Attributes

      + +

      So far you have used html tags to specify CSS rules. For example,

      +
      h2 { 
      +  font-size: 40px;
      +  color: pink;
      +}
      +
      +

      will turn all your <h2> massive and pink.

      + +

      It is often useful to be able to make CSS rules more specific, so you can apply different styles to different parts of the page. One common way to do this is to target specific html attributes - in particular id and class.

      + +

      The id and class attributes

      + +

      HTML tags can have attributes which provide additional information about the element. You’ve aready seen some examples of this:

      +
      <a href="http://www.facebook.com">
      +<img src="cat_pic.png">
      +
      +

      Both href and src are examples of html attributes. They are written in pairs with their values: attribute="value".

      + +

      There are some attributes that can be added to any tag. Two examples of these are id and class:

      +
      <h2 id="products_title">Our scrumptious puddings</h2>
      +
      +<ul id="products_list">
      +  <li class="product_item">Black forrest gateau</li>
      +  <li class="product_item">Rasberry lemon swirl cheesecake</li>
      +  <li class="product_item">Sticky toffee pudding</li>
      +  <li class="product_item">Death-by-chocolate cake</li>
      +</uk>
      +
      +

      Both id and class are used to add some information to the HTML tags. The key difference is that id should specify a unique element on the page, whereas multiple elements can share the same class.

      + +

      CSS lets you target the id and class attributes in special ways:

      +
      /* make the h2 with id="products_title" purple */
      +h2#products_title { color: purple; }
      +
      +/* remove the bullets from all li with class="product_item" */
      +li.product_item { list-style-type: none; }
      +
      +

      The id is targeted by adding #id_value to the tag and the class is targeted by adding .class_value to the tag.

      + +

      It is also possible to target any items with a given class or id by leaving out the HTML tag:

      +
      /* make any element with id="products_title" purple */
      +#products_title { color: purple; }
      +
      +/* make any element with class="product_item blue" */
      +.product_item { color: blue; }
      +
      +

      Divs and spans

      + +

      There are two important HTML tags, that we didn’t use last week: <div> and <span>. Both are really useful when it comes to using HTML attributes to target CSS classes.

      + +

      <div> stands for division and is used to break the page up into different parts. It is a ‘block-level’ element, which means that it will start a new line before and after it.

      + +

      <span> can be used to apply classes and ids to certain bits of text. It is an ‘inline’ element, which won’t start a new paragrah before or after.

      +
      <div id='info_section'>
      +  <p>This is a paragraph in the info section. We can use a span to target <span class='important'>certain bits of important text</span>.<p>
      +</div>
      +
      Task: +
        +
      1. Open the file html2/exercise2.html in Sublime Text and Chrome.
      2. + +
      3. Continue until your page looks like html2/exercise2_solution.png
      4. +
      +
      +
      + + +
      + + +

      External stylesheets

      + +

      So far you have written your CSS rules directly in the head section of your html page:

      +
      <!DOCTYPE html>
      +<html>
      +  <head>
      +  	<title>My page</title>
      +  	<style type="text/css">
      +  	  h1 { color: red; }
      +  	</style>
      +  </head>
      +
      +  <!-- body goes here -->
      +
      +</html>
      +
      +

      We did this to make your first experiments with CSS quick an easy. In a live site it is considered bad practice to put your CSS inside the head section: Typically a site will have one set of styles that apply to all the pages. By separating these CSS rules into their own file you (a) reduce repetition in your code and (b) reduce the amount of information that has to be sent to the browser for each page - if the CSS file applies to the whole site, it only needs to be sent to the visitor once.

      + +

      To link to an external CSS file you can do the following:

      +
      <!DOCTYPE html>
      +<html>
      +  <head>
      +  	<title>My page</title>
      +  	<link rel='stylesheet' type='text/css' href='path/to/my_css_file.css'>
      +  </head>
      +
      +  <!-- body goes here -->
      +
      +</html>
      +
      +

      Linking to other files

      + +

      Linking to other files (stylesheets, javascript files, images) can be done in several ways, just like linking to another page. Say you have the following directory structure:

      + +
      first_site
      +|
      +---- index.html
      +|
      +---- images
      +|    |
      +|    ---- background.jgp
      +|
      +---- stylesheets
      +     |
      +      ---- main.css
      + +

      and you’re going to deploy your site to “http://www.my_first_site.com”. Suppose you want to link to main.css from index.html and to background.jpg from main.css. There are three different styles of links you can use:

      + + + +

      Absolute external links include the complete url to the resource you’re linking to. Absolute links start with either http:// or https://.

      +
      <!-- in index.html -->
      +<link rel="stylesheet" type="text/css" href="http://www.my_first_site.com/stylesheets/main.css">
      +
      /* in main.css */
      +body {
      +  background-image: url("http://www.my_first_site.com/images/background.jpg");
      +}
      +
      +

      Absolute external links can be used to link to resources held on different sites, but wouldn’t usually be used for links within your own site. They’re a bit fragile - if you change your domain name all the links will break. They also won’t work when you’re developing locally.

      + + + +

      Root-relative links contain the path to the resource relative to the site’s root. The site’s root is (roughly) the folder that contains the site - in this case, first_site. Root-relative links begin with a /:

      +
      <!-- in index.html -->
      +<link rel="stylesheet" type="text/css" href="/stylesheets/main.css">
      +
      /* in main.css */
      +body {
      +  background-image: url("/images/background.jpg");
      +}
      +
      +

      Root-relative links are a bit more flexible than absolute external links: e.g. if you change your domain name everything will still be fine. They’re sometimes useful for your own static sites, but probably won’t work when developing locally (because the root will be taken to be the root of your file system and not the folder containing the site!).

      + + + +

      Document-relative links contain the path to the resource relative to the file where the link is written. Document-relative links don’t begin with /:

      +
      <!-- in index.html -->
      +<link rel="stylesheet" type="text/css" href="stylesheets/main.css">
      +
      /* in main.css */
      +body {
      +  background-image: url("../images/background.jpg");
      +}
      +
      +

      To link to the stylesheet from index.html we use stylesheets/main.css which says “look in the same folder I’m in (first_site) and find a folder called styleheets and a file in it called main.css”.

      + +

      To link to the image from the stylesheet is slightly more complicated: we use ../images/background.jpg. This means “go to the folder above the one I’m in (I’m in stylesheets, so that’s first_site) and find a folder called images and a file in it called background.jpg”.

      +
      +
      +

      Important to know

      +
      +
      + In document-relative links (and in many other places e.g. command line navigation) +
        +
      • . means in the folder that I'm in
      • +
      • .. means in the folder above the one that I'm in
      • +
      +
      +
      +

      Relative links are the most flexible - they will work on your local file system. The only think you have to be careful about is moving your files into different folders, which can cause links to break.

      + +

      You should be using relative local links in these exercises.

      + +

      For a recap of all this, read this article.

      +
      Task: +
        +
      1. Return to exercise1.html and separate the CSS out into a separate file (called exercise1.css).
      2. + +
      3. Check that the CSS still shows up when you view the site in the browser.
      4. + +
      5. Make a change in exercise1.css and check that you can see that in the browser. (You might need to refresh the page a few times).
      6. +
      +
      +
      + + +
      + + +

      Homework

      + +

      Finishing off

      +
      Task: + +

      Finish off both CSS exercises from class. Check your solutions online:

      + +
        +
      • Find the HTML2 repository on Code61's github page.
      • +
      • In the `branch` dropdown (just above the list of files) select the `solution` branch.
      • +
      • Click on the files below to see the solution
      • +
      +
      +

      Review

      +
      Task: + +

      Watch this video from General Assembly, which recaps developing locally and deploying to BitBalloon.

      + +
      +

      Buy a domain name

      + +

      Your domain name will be used to point towards your personal website for the course - it’s up to you exactly what this will be about. You might want to use this opportunity to create a basic ‘personal landing page’ saying a bit about yourself and where to find more information. Or you might want to put up a blog. Alternatively if you want you can put up a page about something you are interested in (or your dog). You will need to pick a domain name accordingly!

      + +

      To buy a domain name you need to visit a domain registrar. Examples are:

      + + + +

      There probably won’t be a huge difference in price between these sites. You might be able to find a special offer on one of them if you shop around a bit though. Ultimately the domain you choose isn’t that important for the course - the whole point is to practice pointing a domain name towards a server.

      +
      Task: +
        +
      1. Buy your own domain name.
      2. + +
      3. Follow these instructions to point your custom domain towards your code on BitBalloon.
      4. +
      +
      +

      More HTML/CSS

      +
      Task: +
        +
      1. Complete the whole of Project 3 on the [General Assembly Dash](https://dash.generalassemb.ly/projects) site.
      2. +
      3. Make some changes to your `first_site` based on what you've learnt. Update the online version of your site, by re-uploading to BitBucket.
      4. +
      5. (Optional) Do the projects from the [Codecademy Web Track](http://www.codecademy.com/tracks/web) Sections 7, 8 & 9.
      6. +
      7. (Optional) Read [this article](https://www.inkling.com/read/dreamweaver-cs6-missing-manual-david-sawyer-mcfarland-1st/chapter-4/understanding-links) about absolute vs. relative links.
      8. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c1s3/index.html b/c1s3/index.html new file mode 100644 index 0000000..b752eff --- /dev/null +++ b/c1s3/index.html @@ -0,0 +1,468 @@ + + + + + + Web Fundamentals 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      What's hard about CSS?

      + +

      You’ve seen quite a bit of CSS now; it all seems quite straightforward - you write some css, tweak it ‘til it looks good and you’re done! In theory this is exactly how CSS works and is why CSS is brilliant.

      +
      + +
      +

      Unfortunately, the realities are not quite so straightforward. Different browsers will render CSS with subtle differences. Take a look at the cat picture above. The styling is relatively simple - all we’ve done is add a border and a shadow. The following CSS will probably do this in your browser:

      +
      .img-polaroid {
      +  padding: 4px;
      +  border: 1px solid rgba(0, 0, 0, 0.2);     /* transparent black border */
      +  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      +}
      +
      +

      However, to get this effect in all browsers you need the following:

      +
      .img-polaroid {
      +  padding: 4px;
      +  background-color: #fff;
      +  border: 1px solid #ccc;                           /* grey border for browsers that can't do transparency */
      +  border: 1px solid rgba(0, 0, 0, 0.2);             /* put the transparency after for browsers that do */
      +  -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* some browers only understand webkit box shadow */
      +     -moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); /* others need this */
      +          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      +}
      +
      +

      Just because your site looks good in Chrome, doesn’t mean it will look good in Internet Explorer. Making your site look good (or even presentable) in multiple browsers takes time, effort and experience.

      + +

      What else is hard about CSS?

      + +

      About 5 years ago, ‘all’ you would have had to worry about is the cross-browser display issues. Since then, the mobile web has exploded and you have another (far more important) concern: how will your site look when viewed on a mobile?

      + +

      Making webpages that look good when viewed at multiple different sizes is a whole new level of complexity.

      + +

      Should I just give up then?

      + +

      You might be the sort of person who relishes this sort of challenge - if so, great! If not, help is at hand

      + +
      + + +
      + + +

      Twitter Bootstrap

      + +

      Twitter Bootstrap is set of CSS (& Javascript) files, released by the makers of Twitter.

      + +

      Twitter Bootstrap is a set of ready-made CSS files that provide solutions to common presentation requirements in a cross-browser and responsive way. To make use of Twitter Bootstrap, you need to do two things:

      + +
        +
      1. Link to the Twitter Bootstrap stylesheet in the head of your html page.
      2. + +
      3. Attach the relevant Twitter Bootstrap class to you html element.
      4. +
      + +

      An example: making a stripy table

      + +

      Suppose you want a Zebra-esque table like this fine specimen:

      + + + + + + + + + + + + + + + + + + + + + + + + +
      I am aZebra table!
      Look at mystripes.
      Do you find thembeautiful?
      Do you find themmesmerising?
      Wooaahh .... such stripiness!
      +

      You have a look at the Twitter Bootstrap table documentation and discover that you need to add the table table-striped class to the <table> tag:

      +
      <table class="table table-striped">
      +  ...
      +</table>
      +
      +

      This will apply the relevant CSS rules from the bootstrap CSS file. If you’re interested, you can go into Developer Tools and view the rules that apply e.g.

      +
      /* from line 1950 of bootstrap.css */
      +
      +.table-striped tbody tr:nth-child(odd) td,
      +.table-striped tbody tr:nth-child(odd) th {
      +  background-color: #f9f9f9;
      +}
      +
      +

      Responsive design

      + +

      Responsive design means designing your sites so that they look good on all screen sizes.

      + +

      Twitter Bootstrap promotes a ‘mobile first’ philosophy, encouraging you to design your site so that it looks good at all sizes from the very beginning. It provides a lot of useful CSS that helps you to do this.

      + +

      We’re not really going to cover responsive design in depth in class, but the Bootstrap docs do a good job of explaining what’s possible. Take a look at the grid system as an example.

      +
      Task: + +

      The aim of the rest of this session will be to create the website for "Sam's Sarnies" using Twitter Bootstrap.

      + + +
        +
      1. +Go to the github repository for the bootstrap exercise. Download the code into your coding_course folder (by clicking 'Download ZIP' in the bottom right). +
      2. +
      3. +Open bootstrap_exercise/index.html in your browser. +
      4. +
      5. +Go to the Bootstrap website (it's hosted at github, like your first_site) and click the Download Bootstrap button (not the Download Source). +
      6. +
      7. +Unzip and copy the dist folder into the bootstrap_exercise folder. +
      8. +
      9. +Open index.html in Sublime Text and Chrome. +
      10. +
      11. +Add a link to the twitter bootstrap stylesheet into index.html + + +
        <link href='dist/css/bootstrap.css' rel='stylesheet'>
        +
        + +Note that you're using a document-relative link to a file two subfolders down. + +
      12. +
      13. +Refresh the page in Chrome. Notice how the fonts have changed. +
      14. +
      15. +Add the following line to the head section: + + +
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        +
        + +as suggested in the CSS / Overview section of the Bootstrap docs. +
      16. +
      +
      +
      + + +
      + + +

      Bootstrap layout

      + +

      Bootstrap gives you several options on how to layout your page. To find out more take a look at the Grid system docs on the Bootstrap site. Some of these options will work out-of-the-box with responsive design - so that you can create a single html page which will look good whether viewed on a laptop, tablet or phone.

      + +

      We’ll just look at a few of the most important layout options here:

      + +

      Page margins

      + +

      Bootstrap makes it easy to center content on your page and provide sensible page margins. To do this make use of the container class:

      +
      <body>
      +  <div class="container">
      +
      +    <!-- page content goes here -->
      +
      +  </div>
      +</body>
      +
      +

      Columns

      + +

      Bootstrap works on a grid layout, with 12 columns (by default). You can create a column layout with the row and span classes:

      +
      <div class='row'>
      +    <div class='col-sm-4'>
      +        <!-- First column content -->
      +    </div>
      +    <div class='col-sm-4'>
      +        <!-- Second column content -->
      +    </div>
      +    <div class='col-sm-4'>
      +        <!-- Third column content -->
      +    </div>
      +</div>
      +
      +

      The number after the col-sm- determines how many of the 12 grid columns that page column takes up. The sm bit determines the width at which the columns will collapse on top of each other (which is useful when viewing your site on a phone). For more information see the Grid system docs.

      +
      Task: +
        +
      • Add a div class='container' around the page content.
      • +
      • Create a row at the top of the page, with two columns, with the left twice as wide as the right. Put the h1 in the left column and the img src='images/sandwich.png' on the right.
      • +
      • Create a row with three equal colums to hold each of 'The Buzz' divs.
      • +
      +
      +
      + + +
      + + +

      More Bootstrap

      + +

      Typography

      + +

      Skim through the typography section of the bootstrap docs.

      +
      Task: +
        +
      1. Change the quotes in 'The Buzz' to use blockquotes. (Don't worry about the vertical grey lines - we'll remove those later.)
      2. + +
      3. Change the paragraphs in 'Our mission' to be lead body copy.
      4. +
      +
      +

      Badges and Buttons

      + +

      Check out the buttons section (CSS > Buttons).

      +
      Task: + +
        +
      1. Change the 'Send' button to a success button:
      2. +
      + + +
      <button class='btn btn-success'>Send</button>
      +
      +

      You might also need btn-small in the Recent Activity section.

      + +
        +
      1. Make the social links at the bottom in to large buttons (we'll colour them later):
      2. +
      +
      <button class='btn btn-lg'>Send</button>
      +
      + +
      +

      Images

      + +

      Have a look at the image section of the Bootstrap docs (CSS > Images).

      +
      Task: +
        +
      1. Make the images in 'The Buzz' round, by adding the img-circle class.
      2. + +
      3. You can center the image by adding the alignment class text-center.
      4. + +
      5. Change the main sandwich image into a img-responsive, as described in the responsive images section. Try resizing your browser and see how it changes size.
      6. +
      +
      +
      + + +
      + + +

      Modifying Bootstrap

      +
      +Warning: Bootstrap has been designed and heavily tested for good cross-browser compatibility. Unless you know what you're doing or have a lot of time, it's probably best to stick with their layout and tweak small things e.g. fonts and colours. Just because it looks great in your browser doesn't mean it will look great in everyone's! +
      +

      If you’re going to modify Bootstrap don’t touch the Bootstrap files. Instead create a new css file of your own to overwrite anything you don’t want. This means when a new version of Bootstrap comes out you can upgrade by dragging the new version over the top of the old, without losing any modifications.

      +
      Task: + +
        +
      1. Create a file called main.css and write the following CSS:
      2. +
      + + +
      #social-buttons button {
      +  color: white;
      +}
      +.btn-twitter {
      +  background-color: #00acee;
      +  border-color: #009ad5;
      +}
      +.btn-facebook {
      +  background-color: #4868ac;
      +  border-color: #314776;
      +}
      +.btn-pinterest {
      +  background-color: #b62f26;
      +  border-color: #b62f26;
      +}
      +
      +
        +
      1. Link this file into the head of index.html underneath your link to bootstrap.
      2. + +
      3. What happens? Notice how in the first rule we've selected only those buttons that exist inside an element with id=social-buttons.
      4. +
      +
      +

      Changing the background

      +
      Task: +
        +
      1. +Change the background of the jumbotron to be the image fruit-and-veg.png by adding the css + +
        .jumbotron {
        +  min-height: 600px;
        +  background-image: url('images/fruit-and-veg.jpg');
        +  background-size: cover;
        +  background-attachment: fixed;
        +}
        +
        + +
      2. + +
      3. +This doesn't look quite right. The problem is that the jumbotron is it is inside the div class='container'. You can change this by moving it inside: + +
        <div class="jumbotron">
        +  <div class="container">
        +
        +  </div>
        +</div>
        +
        + +Similarly you will now need to create new containers inside the div id='buzz' and div id='mission'. +
      4. +
      5. +Change the background color of the mission section to rgba(32, 35, 41, 0.9) and the font colour to #ddd +
      6. +
      +
      + + +

      Browse through the navbar section of the Bootstrap docs.

      +
      Task: +
        +
      1. +

        Look at the html for the basic starter template.

        +
      2. + +
      3. +

        Use it to add a navbar to your site.

        +
      4. + +
      5. +

        Make it a navbar-fixed-top. You will need to add

        + +
         body { padding-top: 70px; }
        + +

        to main.css.

        +
      6. + +
      7. +

        Add a search box to the navbar. Use the pull-right class to put it on the right hand side.

        +
      8. +
      +
      +

      Other things

      + +

      There are various other changes you will need to make your site look like the example. Try and figure out what these are by examining the html in the Developer tools.

      +
      Task: +
        +
      1. Make any other changes necessary to make your site look like the example
      2. + +
      3. If you get stuck check by looking at the gh-pages branch on the github repo.
      4. +
      +
      +
      + + +
      + + +

      Homework

      + +

      Finishing off

      +
      Task: + +

      Finish off the bootstrap_exercise from class

      + +
      +

      Personal site

      +
      Task: + +

      Continue work on your personal site. You might want to think about using Twitter Bootstrap!

      + +
      +

      Further reading on CSS

      +
      Task: +
        +
      1. (Optional) Read this article which explains about CSS Specificity (and more).
      2. + +
      3. (Optional) Read this article on CSS selectors.
      4. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c1s4/index.html b/c1s4/index.html new file mode 100644 index 0000000..abdc49b --- /dev/null +++ b/c1s4/index.html @@ -0,0 +1,125 @@ + + + + + + Web Fundamentals 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Recap

      + +

      CSS

      + +

      We’re now going to add a separate CSS file to your first_site. (If you already have one, that’s fine - just add another one.)

      +
      Task: +
        +
      1. Create a new file in sublime text and save it as main.css in your first_site folder.
      2. + +
      3. Put a CSS rule in that file (e.g. h1 {color: red})
      4. + +
      5. Put a link to the file from the head section of your index.html file.
      6. + +
      7. Make sure you can see the style when you open index.html in chrome.
      8. +
      +
      +
      + + +
      + + +

      Google Analytics

      + +

      Google Analytics is an analytics service provided for free by Google. It allows you get an overview of how many people are visiting your site, where they come from, what they do on your site, and much more.

      + +

      How it works

      + +

      To use Google Analytics you need to place a snippet of javascript (that they provide) on each of the HTML pages on your site. When a user visits the page, the javascript sends a message to the Google Analytics site logging the visit.

      +
      Task: +
        +
      1. Set up a Google Analytics account. You want to choose the default 'Universal Analytics' option.
      2. + +
      3. In the Admin section, create a new account for your personal site.
      4. + +
      5. Following the instructions, install the analytics code on all the pages of your site.
      6. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: + +

      Continue to work on your first_site until it's something you can be proud of!

      + +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c2s1/index.html b/c2s1/index.html new file mode 100644 index 0000000..b97bce5 --- /dev/null +++ b/c2s1/index.html @@ -0,0 +1,393 @@ + + + + + + Web Fundamentals 2 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Getting code from Github

      + +

      Git recap

      + +

      Getting code from github

      + +

      In previous sessions we’ve used git to pull code down from github. We’re going to start this session by doing the same again:

      +
      Task: +
        +
      1. +

        Go to the command line and navigate to your coding_course folder

        +
      2. + +
      3. +

        Clone the project https://github.com/tomclose/cfgmt2013_first_site:

        + +
         $ git clone https://github.com/tomclose/cfgmt2013_first_site toms_site
        +
      4. +
      +
      +

      You should now see a new file called toms_site in your coding_course folder, and be able to open toms_site/index.html in your browser. The clone operation has copied a local version of the repository onto your computer.

      + +

      Git will help you keep this local copy updated. If I’ve made some changes and pushed them up to github, you just need to run

      + +
      $ git pull
      + +

      to pull them down onto your laptop.

      +
      Task: +
        +
      1. +

        Open toms_site/index.html in Sublime Text

        +
      2. + +
      3. +

        Wait for me to make a change and push it to gihub

        +
      4. + +
      5. +

        Pull down the changes and make sure you can see them in your browser:

        + +
        $ git pull
        +
      6. +
      +
      +
      + + +
      + + +

      Conflicts

      +
      Task: +
        +
      1. +

        Open toms_site/index.html in your code editor, and change the page heading (inside &lt;h1&gt;) to something of your choosing. (At the same time I'll also make a change). When you're done, commit your change to the local repository:

        + +
         $ git add --all
        + $ git commit -m &quot;Changed heading&quot;
        +
      2. + +
      3. +

        Wait while I push my own change to the &lt;h1&gt; element.

        +
      4. + +
      5. +

        Pull down my changes

        + +
         $ git pull
        +
      6. +
      +
      +

      You should now have a message telling you that you have a merge conflict. This is because our two changes have been made at the same time, so git is unabled to work out which is the up-to-date one to keep. If you look in your file you should see things that look like

      + +
      <<<<<<< HEAD
      +    <h1 class="special">My Page</h1>
      +=======
      +    <h1 class="special">Tom C's page</h1>
      +>>>>>>> d76d5a62894057f9c5a4dce0fe5f25110eddd24f
      + +

      To fix the merge conflict you need to edit this by hand, picking the version you want and then do:

      + +
      $ git add --all
      +$ git commit -m "Fixed conflicts"
      +
      Task: +
        +
      1. +

        Delete the conflict markers (&lt;&lt;&lt;&lt;, =====, &gt;&gt;&gt;&gt;) from index.html (using Sublime text)

        +
      2. + +
      3. +

        Delete the version of the heading that you don't want.

        +
      4. + +
      5. +

        On the command line:

        + +
         $ git add --all
        + $ git commit -m &quot;Fixed conflicts&quot;
        +
      6. + +
      7. +

        To have a look at what you've just done:

        + +
         $ gitk --all
        + +

        or

        + +
         $ git log --pretty --graph --oneline
        + +

        You should see how the two versions branched and came back together.

        +
      8. +
      +
      +
      + + +
      + + +

      Github collaboration

      + +

      There are a few options for collaborating with others using Git.

      + +

       One-way sharing

      + +

      As we all know, one-way sharing isn’t really sharing at all. Even so, this is the easiest example to look at - in fact we’ve been doing it almost from the first session of the course.

      + +

      In one-way sharing, there is one ‘master’ repository on GitHub that everyone can read from, but only one person can write to:

      +
      + +
      +

      Forking

      + +

      One of the options for sharing your changes with me, is for you to publish your repository too. I can then pull your changes down just as you pulled mine.

      +
      + +
      +

      Notice that this situation is symmetric - my repositories are equivalent to yours. This makes it a suitable model for many open source projects, where the project maintainer might change over time.

      + +

      Github makes this model easy by providing a ‘forking’ button. Forking is a quick an easy way make a copy of my repository on GitHub so that you can then pull and push to it.

      + +

      Sharing

      + +

      The other way or collaborating with git is the ‘sharing’ model: one person puts the repository on github and gives other people permissions, so you can all push to the same place.

      +
      + +
      +

      To do this on github, go to your forked landing page repository and click on ‘Settings’ on the right hand side. Then go to ‘Collaborators’ and add your team members’ github usernames.

      + +


      + +

      You can find out more about these different workflow option from the Git book.

      + +
      + + +
      + + +

      Joint project

      + +

      The purpose of this project is to create a shared html page to serve as a ‘cheat sheet’ for all the different commands you’ve learnt in the course so far (e.g. ls, git add --all etc.). You will need to be in groups of three.

      +
      Task: +
        +
      1. +

        Person A should set up a new project on their laptop:

        + +
          +
        1. Create a new folder called group_cheatsheet in your coding_course folder
        2. + +
        3. Create a file in that folder called index.html with some simple html in it.
        4. +
        +
      2. + +
      3. +

        Person A should then set it up as a git repository

        + +
        $ cd group_cheatsheet
        +$ git init
        +$ git add --all
        +$ git commit -m &quot;Initial import&quot;
        +
      4. + +
      5. +

        Person A creates a new repo on github. To do this you need to log in at github.com and select "Create a new repo". You should call the repository group_cheatsheet.

        +
      6. + +
      7. +

        Person A should then push their code up to github following the instructions on github. You want to "Push an existing repository from the command line" - the instructions at the bottom of the page. You should end up pasting a command like

        + +
        # Warning: these commands won&#39;t work. You need copy the right ones from GitHub.
        +git remote add origin https://github.com/username/blah.git
        +git push -u origin master
        +
      8. + +
      9. +

        Person A then needs to add everyone else as collaborators by going to Settings &gt; Collaborators on the repo page

        +
      10. + +
      11. +

        Everyone else should then clone the project:

        + +
          +
        1. +

          Go to the repo's github page

          +
        2. + +
        3. +

          Copy the ssh link from the box on the page

          +
        4. + +
        5. +

          In your coding_course folder do

          + +
          git clone paste_the_repo_link_here
          +
        6. +
        +
      12. + +
      13. +

        Person B should then download Twitter Bootstrap and put it in the group_cheatsheet folder

        +
      14. + +
      15. +

        Meanwhile Person C should add more content to the page's html

        +
      16. + +
      17. +

        Person B should add their changes and push up to github:

        + +
         git add .
        + git commit -m &quot;Added twitter bootstrap&quot;
        + git push
        +
      18. + +
      19. +

        Person C should then add their changes and try and push up:

        + +
         git add .
        + git commit -m &quot;Edits to index.html&quot;
        + git push
        +
      20. + +
      21. +

        This will probably fail, as C won't have B's changes. To fix this Person C needs to pull and merge (the merge will probably happen automatically if you haven't changed the same files). They should then push again:

        + +
         git pull
        +
        + # fix any merge conflicts if necessary, then add and commit the changes
        +
        + git push
        +
      22. + +
      23. +

        Continue to work on the cheatsheet together!

        +
      24. +
      +
      +
      + + +
      + + +

      Homework

      + +

      Tell us about your site

      +
      Task: + +

      Tell us about your first site by filling in this form. If you're still having problems getting it to display online or pointing your url to it, ask in the forum!

      + +
      +

      Work on your group cheatsheet

      +
      Task: +

      Continue to add information to your group cheatsheet. At the very least you should

      + +
        +
      1. Have a section for the basic command line commands.
      2. + +
      3. Have a section for the basic git commands.
      4. + +
      5. Have each pushed to the shared repository at least twice by next week.
      6. +
      +
      +

      Learn to hate your track pad

      + +

      From now on, try to touch your mouse/trackpad as little as often - it will make you quicker and more effective.

      +
      Task: +
        +
      1. Practise using Cmd-tab (Mac) or Ctrl-tab (Windows) to move between programs.
      2. + +
      3. Practise using Cmd-space (Mac) or ?? (Windows) to open programs by typing their names.
      4. + +
      5. Practise using short cut keys: +
          +
        • Cmd-s (Mac) or Ctrl-s (Windows) for saving
        • + +
        • Cmd-r (Mac) or Ctrl-r (Windows) to refresh the browser
        • +
        +
      6. +
      +
      +

      Learn to love your editor

      + +

      Over the rest of the course you will be spending a lot of time in Sublime Text. Investing the time to learn to use it more effectively now will pay off!

      +
      Task: + +

      (Optional) Take a look through the Sublime text screencasts at Tuts+.

      + +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c2s2/index.html b/c2s2/index.html new file mode 100644 index 0000000..18402f0 --- /dev/null +++ b/c2s2/index.html @@ -0,0 +1,225 @@ + + + + + + Web Fundamentals 2 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      jQuery

      + +

      This is meant to serve as a really quick introduction to jQuery - more to enable you to learn more, rather than to teach you anything in particular.

      + +

      What is jQuery

      + +

      Javascript is the third main client side technology (along with HTML and CSS). Unlike HTML and CSS, which are mark-up languages, Javascript is a programming language - you can use it to do calculations (and pretty much anything you want!).

      + +

      jQuery is a javascript library that is useful for building interactive webpages. When you use jQuery, it’s a bit like you’re using a special version of javascript.

      + +

      jQuery is so common in webpages that, for beginners, ‘learning javascript’ has in many cases become ‘learning jQuery’. This is the approach that we’re going to take in this course.

      + +

      Getting jQuery

      + +

      jQuery is just a javascript file that can be downloaded from the jquery downloads page. There are a couple of different versions - I’d go for the latest. For each version you can either get the normal code, which is useful for development, or the minified code, which has had all the space (and other stuff) taken out to make it as small as possibile, so it downloads quicker.

      + +

      Once you’ve downloaded the file and saved it in your site folder, you need to link to it in your page. For the time being we’ll do this in the head (you can improve page-load times by moving your javascript to the bottom of the page, but we won’t bother with this at the moment).

      +
      <!DOCTYPE html>
      +<head>
      +  <script src="jquery.js"></script>
      +  <!-- any other stuff e.g. stylesheet links -->
      +
      +

      Using jQuery

      + +

      You can do a lot of stuff with jQuery. Here we’ll just look at the basics: selecting elements on the page and doing stuff with them.

      + +

      You can experiment with jQuery using the Console section of the Chrome developer tools. You will need to be on a page where jQuery is loaded (e.g. these course notes or the demo page you will download in the exercise).

      + +

      One of the nice things about jQuery is its ability to select elements via their CSS selectors. To select elements jQuery uses the $() function. For example:

      +
      $('li')               // selects all the li elements on the page
      +$('li.important')     // selects all the li with class="important"
      +$('#main-title')      // selects the element with id="main-title"
      +
      +

      jQuery then has several ways of manipulating those elements:

      +
      $('h1').hide()
      +$('h1').show()
      +$('h1').css('color', '#f00')
      +$('h1').css('color', '#ff0')
      +$('h1').css('font-size', '80px')
      +$('h1').css('font-size', '8px')
      +$('h1').css('text-align', 'right')
      +$('h1').fadeOut()
      +$('h1').fadeIn()
      +
      +

      You can find out more about the options available to you in the jQuery docs.

      +
      Task: +
        +
      1. +

        Clone down the jQuery demo code:

        + +
         git clone https://github.com/tomclose/jquery_intro.git
        +
      2. + +
      3. +

        Open index.html in Chrome.

        +
      4. + +
      5. +

        Open the Chrome developer tools and switch to the Console panel.

        +
      6. + +
      7. +

        In the console try the following:

        + +
         $(&#39;h1&#39;).hide()
        + $(&#39;h1&#39;).show()
        + $(&#39;h1&#39;).css(&#39;color&#39;, &#39;#f00&#39;)
        + $(&#39;h1&#39;).css(&#39;color&#39;, &#39;#ff0&#39;)
        + $(&#39;h1&#39;).css(&#39;font-size&#39;, &#39;80px&#39;)
        + $(&#39;h1&#39;).css(&#39;font-size&#39;, &#39;8px&#39;)
        + $(&#39;h1&#39;).css(&#39;text-align&#39;, &#39;right&#39;)
        + $(&#39;h1&#39;).fadeOut()
        + $(&#39;h1&#39;).fadeIn()
        +
      8. + +
      9. +

        Can you make the list items go green?

        +
      10. +
      +
      +
      + + +
      + + +

      jQuery resources

      + +

      Obviously, we’ve only just scratched the surface of what’s possible with javascript/jQuery. Things get a lot more interesting when you can create bits of javascript to be run in response to a user action. This allows you to build up interactions like “when the user clicks the submit button, check that their email is a valid email, if it isn’t make the field go red and add the words ‘email is invalid’ at the bottom of the form”.

      + +

      Learning more jQuery

      + +

      We won’t be spending any more time on jQuery this course, and will be moving onto backend stuff next term. If you want to learn more about jQuery you might want to try some of the following resources:

      + + + +

      jsFiddle

      + +

      jsFiddle is a site which allows you to try out small bits of HTML, CSS and Javascript. It’s a really useful tool for getting good help with javascript (and HTML/CSS) online: If you’re having a problem:

      + +
        +
      1. Create a jsFiddle showing what you’ve tried.
      2. + +
      3. Post on StackOverflow describing the problem, with a link to the jsFiddle.
      4. +
      + +

      People will be able to help you better if they can see the code themselves. Often they will respond with a working jsFiddle (as in this example)

      + +
      + + +
      + + +

      Ruby check

      + +

      Next term we’re going to be looking at backend development in ruby. You will need to have ruby installed. You should check whether you have this now:

      +
      Task: +
        +
      1. +

        On the command line (in any folder) type:

        + +
         ruby --version
        + +

        It should tell you the version of ruby that's installed. If it doesn't say anything you're in trouble!

        +
      2. +
      +
      +

      You can have a bit of a play with ruby now if you want: on the command line type irb (this stands for interactive ruby). You’ll end up in a ruby session (a bit like if you’ve used Matlab). Try the following:

      +
      1+2
      +3-4
      +5*6
      +10/5
      +9/5
      +9/5.0
      +2**3
      +2**19283
      +
      +x = 5
      +y = 6
      +x + y
      +
      +(1..10).each {|n| puts n }
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c3prep/index.html b/c3prep/index.html new file mode 100644 index 0000000..f2949f5 --- /dev/null +++ b/c3prep/index.html @@ -0,0 +1,495 @@ + + + + + + Course Preparation + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Installing Ruby: Easy Way

      + +

      Ruby is a programming language that we will be the focus of the course. In order to run ruby programs on your computer you need to have the language, and various development tools, installed on your laptop. That’s what we’re going to do now.

      + +

      The easiest way to install ruby is to use the railsinstaller, which will install ruby, Ruby on Rails, git and a few other things (don’t worry if you already have git - it’ll be ok!). Ruby on Rails is a framework for building web applications quickly and easily, built using Ruby. We won’t actually be using Ruby on Rails in this course, but it’s useful to have it for the future.

      + +

      It’s important to realise that git, Ruby and Ruby on Rails are not ‘programs’ in the sense that you are probably used to. There won’t be any icons for ruby, git or Ruby on Rails. They’re the sort of programs you run from the command line, rather than applications that you click on. More on this later

      + +

      If you’re on a mac, the next tab has instructions on a different way to install ruby. Have a look at these before deciding which method you want to go ahead with.

      +
      Task: + +

      Go to http://railsinstaller.org/ and follow the instructions for your operating system (choosing all the defaults they give). You want the Ruby 1.9 version.

      + +
      +

      Windows notes:

      + +

      At the final stage, there will be a tick box asking if you want to “Configure git and ssh”. Make sure this box is ticked. Follow the instructions and fill in your name and email (this is only used for your git commits).

      + +

      It will also tell you something about having copied your ssh key to the clipboard. This might or might not be true. In any case, don’t worry as we’re moving on to this next.

      + +

      Mac notes:

      + +

      You will need to know which version of OS X you are running: 10.8 (Mountain Lion), 10.7 (Lion), or 10.6 (Snow Leopard). To check this click on the apple symbol in the top left of your screen and select ‘About This Mac’.

      + +

      Did it work?

      +
      Task: +

      You should now have installed git and ruby on your laptop. Check it worked with the following steps:

      + +
        +
      1. +

        Open your command line:

        + +
          +
        • On a Mac open Terminal (Applications > Terminal)
        • + +
        • On Windowns open 'Command Prompt with Ruby on Rails' (this should have been installed by rails installer)
        • +
        +
      2. + +
      3. +

        Type

        + +
         git --version
        + +

        It should look something like this

        + +
         $ git --version
        + git version 1.8.4
        + $ 
        + +

        If it doesn't print out your git version you have a problem - email your instructor!

        +
      4. + +
      5. +

        Type

        + +
         ruby --version
        + +

        It should look something like this

        + +
         $ ruby --version
        + ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.1]
        + $
        + +

        If it doesn't print out your ruby version you have a problem - email your instructor!

        +
      6. +
      +
      +
      + + +
      + + +

      Installing Ruby: Better Way

      + +

      These instructions are for Mac only. On Windows the Easy Way is the Better Way.

      + +

      What’s better about the Better Way?

      + +

      These instructions will take you through installing Ruby and git using an OS X package manager called Homebrew. Once you have Homebrew set up you will be able to quickly and easily install the vast majority of the (free, open-source) software you will need as a developer. Consider this an investment for the future!

      + +

      The first parts of the installation procedure is described in a post by Moncef Belyamani here. [Our Steps 1-3 correspond to their Steps 1-5. We wont be doing their steps 6 onwards.] If you get stuck, please check with these instructions. If you find things that don’t work, please email your course instructor.

      + +

      Step One: Installing Apple’s Command Line Tools

      + +

      Homebrew works by providing automatic recipies to download and compile software for your computer. In order to compile software you need a compiler. Apple provides you with a compiler but doesn’t install it on OS X by default. You will need to do this for yourself. Before you do this you should check you don’t have it already.

      +
      Task: +
        +
      1. +

        Open Terminal (e.g. from your Application folder)

        +
      2. + +
      3. +

        Type

        + +

        gcc –version

        +
      4. + +
      5. +

        If this says something a bit like

        + +

        i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666)

        +
      6. +
      + +

      you have a the gcc compiler installed and can skip to Step Two

      + +
        +
      1. If it says nothing, you need to install it.
      2. +
      +
      +

      If you don’t have a compiler already you need to install Apple’s Command Line Tools - either directly or by installing XCode. The options for doing this are described in the Railsbridge Installfest. Those options are also covered in Moncef’s post as Step 1 - note the special instructions for those on Snow Leopard.

      +
      Task: + +

      If you don't have gcc, install it following one of the sets of instructions above.

      + +
      +

      Step Two: Install Homebrew

      + +

      Once you have the compiler installed it should be mostly plain sailing. To install Homebrew

      +
      Task: +
        +
      1. Go to the Homebrew homepage
      2. + +
      3. Scroll down until you find the 'Install Homebrew' section and follow the instructions. It should be as simple as pasting +

        ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"

        +
      4. +
      + +

      into the terminal.

      +
      +

      If you run into any problems have a check in Step 3 of Moncef’s post.

      + +

      Step Three: Install Git

      +
      Task: +
        +
      1. +

        In the terminal type:

        + +

        brew update brew install git

        +
      2. + +
      3. +

        Close the terminal programme and reopen it.

        +
      4. + +
      5. +

        To check it worked, in the terminal type:

        + +

        git –version

        + +

        It should look something like this

        + +
         $ git --version
        + git version 1.8.4
        + $
        + +

        If it doesn't print out your git version you have a problem - ask in the forum!

        +
      6. + +
      7. +

        Configure your git details by typing

        + +

        git config –global user.name "Your Full Name" git config –global user.email "Your Email Address"

        +
      8. +
      + +

      (replacing "Your Full Name" and "Your Email Address")

      +
      +

      Step Four: Install rbenv

      + +

      If you have a Mac, you actually already have ruby installed on your system. Unfortunately it’s a really old version of ruby. As a developer it is useful to be able to have several versions of ruby on your system, so that you can switch versions between projects if necessary. Rbenv (ruby environment) is a tool to help you do this.

      + +

      Note: if you have ever installed RVM you will need to uninstall it as it won’t play well with rbenv. If you’re following these instructions you probably haven’t ever installed RVM.

      +
      Task: +
        +
      1. +

        In the terminal type:

        + +

        brew install rbenv brew install ruby-build echo 'eval "$(rbenv init -)"' >> ~/.bash_profile

        +
      2. + +
      3. +

        Close the terminal and reopen it.

        +
      4. + +
      5. +

        To check it worked, in the terminal type:

        + +
         rbenv --version
        + +

        It should look something like this

        + +

        $ rbenv –version rbenv 0.4.0 $

        +
      6. +
      +
      +

      Step Five: Install Ruby

      + +

      Having installed rbenv with homebrew, we will now use rbenv to install the latest version of ruby.

      +
      Task: +
        +
      1. +

        In the terminal type:

        + +

        rbenv install 1.9.3-p392

        + +

        This will download and install ruby version 1.9.2-p392

        +
      2. + +
      3. +

        Then type:

        + +

        rbenv global 1.9.3-p392 rbenv rehash

        +
      4. +
      + +

      This will set your system to use the new version of ruby by default.

      + +
        +
      1. +

        To check it worked, in the terminal type:

        + +
         ruby --version
        + +

        It should look something like this

        + +

        $ ruby –version ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.1] $

        +
      2. +
      +
      +

      Step Six: Install Rails

      + +

      You won’t actually need rails this course, but now you’ve installed ruby it’s easy to get it using Rubygems. Rubygems is ruby’s excellent package manager, used for sharing projects written in ruby - more on this later in the course.

      +
      Task: +
        +
      1. In the terminal type: +

        gem install rails gem install bundler

        +
      2. +
      +
      +
      + + +
      + + +

      SSH keys

      + +

      An SSH key gives you a way of connecting to a remote computer without having to type in a password everytime. In the course you will often be pushing code up to GitHub and other locations, and it can get annoying if you continually have to provide your password.

      + +

      In this step we will guide you through creating an ssh key and uploading it to GitHub. This is probably the most complicated step of the installation instructions. Good luck!

      +
      +If you have 'GitHub for Windows' or 'GitHub for Mac' you might already have an ssh key set up. You can check this by logging in to github and clicking 'Account Settings > SSH keys'. If you see a key in the list, you're done and can skip the rest of this page. +
      +

      GitHub itself provides excellent instructions for this step: Github - Generating SSH Keys. We’ll be just providing a few notes to go with those instructions here.

      + +

      (You might see that GitHub recommends using a different connection method: https. We’re going to stick with ssh as (a) it’s good to know how to set up an ssh key and (b) it avoids messing around with the credential-helper.)

      + +

      The basic overview

      + +

      What we’re doing basically has two steps:

      + +
        +
      1. Generate the key on your laptop
      2. + +
      3. Upload the public part of the key to GitHub
      4. +
      + +

      An SSH key comes in two parts. One part is public and can be given to anyone. The other part is private and should be stored safely on your laptop (when generating the key you can and should use a passphrase to protect it). Working together the two parts can accomplish two different purposes:

      + +
        +
      • Anyone who has the public key can encrypt a message so that it can only be read using your private key.
      • + +
      • With your private key you can sign a message such that people with the public key can be sure you sent it.
      • +
      + +

      The keys work using the RSA algorithm. The whole system relies on the fact that it’s easy to multiply large numbers but very hard to factorize them (to undo the multiplication). At least, it will be until someone builds a quantum computer, but that’s another story

      +
      Task: + +

      Create and upload an SSH key to GitHub by following the instructions on GitHub for your operating system.

      + +
      +

      Notes for Windows users

      + +

      If you just ran RailsInstaller you won’t need to generate a key - they did it for you!

      + +

      You will need to do Step 1 on the GitHub ssh key instructions then continue directly to Step 3.

      + +

      Notes for Mac users

      + +

      For some reason RailsInstaller doesn’t seem to generate the key for you on a Mac. You will need to do all the steps from the GitHub ssh key instructions.

      + +
      + + +
      + + +

      Meet the Command Line

      + +

      The command line is a way to interact with your computer programmatically. If you are doing any software development you will need to get to grips with using the command line, as many of the programs you will use will be run from the it, instead of by clicking an icon.

      + +

      Note: when giving you instructions for the command line we will precede them with a $ to represent the command prompt e.g.

      + +
      $ some_command
      + +

      You shouldn’t type the $ sign - just the stuff after it. So for the above instruction you would just type some_command into the command line.

      + +

      Moving around

      + +

      The first thing you will need to get used to is moving around. Start by printing the name of the directory you are in:

      + +
      $ pwd
      + +

      Then have a look at what’s in that directory ( list the contents):

      + +
      $ ls
      + +

      To move up a directory ( change directory ) do

      + +
      $ cd ..
      + +

      To move back into the folder you just left do

      + +
      $ cd name_of_the_folder
      + +

      Your commandline will help you: tab can often be used to auto-complete names of files, the up arrow can be used to cycle through previous commands that you have typed.

      + +

      Creating a directory

      + +

      You can do a lot more on the command line than just move around. We’ll be using the command line a lot over the course. For the time being we just need to create a folder:

      + +
      $ mkdir coding_course
      + +

      Note: choosing names without spaces makes command line navigation easier.

      +
      Task: +
        +
      1. +

        Open your command line:

        + +
          +
        • On a Mac open Terminal (Applications > Terminal)
        • + +
        • On Windows open Command Prompt with Ruby on Rails
        • +
        +
      2. + +
      3. +

        Find out where you are:

        + +
         $ pwd
        +
      4. + +
      5. +

        See what is in the same folder:

        + +
         $ ls
        +
      6. + +
      7. +

        If you are on a Mac move into Documents:

        + +
         $ cd Documents
        +
      8. + +
      9. +

        Practice creating a new folder:

        + +
         $ mkdir my_new_folder
        +
      10. + +
      11. +

        Move into that folder:

        + +
         $ cd my_new_folder
        +
      12. + +
      13. +

        Move back up to the folder above

        + +
         $ cd ..
        +
      14. + +
      15. +

        Move back into the coding course folder. This time don't type out my_new_folder - just type out the first few letters and hit Tab:

        + +
        $ cd my_new_folder
        +
      16. + +
      17. +

        In the Finder (Mac) or My Computer (Windows) find the folder that you just created.

        +
      18. +
      +
      +
      + + +
      + + +

      Meet Ruby!

      + +

      We’ll be using Codecademy to complement the work you’re doing in class. In order to prepare for the first session, please take a look at the first two sections of the Codecademy Ruby track.

      +
      Task: +
        +
      1. Sign up for Codecademy.
      2. + +
      3. Do the Codecademy Ruby track Sections 1 and 2.
      4. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c3s1/index.html b/c3s1/index.html new file mode 100644 index 0000000..5b9ca38 --- /dev/null +++ b/c3s1/index.html @@ -0,0 +1,660 @@ + + + + + + Introduction to Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Introducing ruby

      + +

      Ruby is a programming language. It is different to HTML and CSS, which are just markup languages: in ruby you can do calculations.

      + +

      Ruby is an incredibly powerful and flexible language. It is a modern language - created in the 1990s by Yukihiro Matsumoto (Matz). A large part of his design philosophy is centered around optimizing for developer happiness - making a language that is a pleasure to program in. If you haven’t already programmed in another language, you might not fully appreciate this, but - take it from someone who has - ruby is awesome!

      + +

      Ruby really shot to fame around 2005, due to the Ruby on Rails web framework. Ruby on Rails is a free, open-source web programming toolkit, which makes it really quick and easy to build web applications. Many top startups and sites (e.g. yellowpages.com, airbnb.com, github.com, gocardless.com, grouper.com) are built with ruby on rails - its rapid prototyping capabilities make it one of the go-to choices, especially for startups. The first version of Twitter was built in Ruby on Rails!

      + +

      In this course, we’ll be leaning the basics of ruby, in a web development context. We won’t be using ruby on rails, instead focussing on a simpler framework (called sinatra), which will give you a better understanding of what’s going on behind the scenes and allow you to be far more productive with rails, when you come onto it later.

      + +

      Interactive ruby: irb

      + +

      Ruby is an interpreted language. One of the great things about an interpreted language is that it’s often possible to interact with the interpreter in real time. When you installed ruby, you also got a program called irb (interactive ruby), which allows you to interpret ruby on the command line. To start it you just type irb on the command line.

      +
      001: > 2 + 2
      + => 4 
      +002: > 
      +
      +

      2 + 2 is a ruby expression. The => symbol tells you what value this expression evaluates to. The interpreter has converts expressions to values.

      + +

      If you just type the value 4 into irb, you will see that it will return 4 to you.

      +
      001: > 4
      + => 4 
      +002: > 
      +
      +

      Like all values in ruby, 4 is also an expression - it just evaluates to itself.

      + +

      So far you’ve only seen values that are numbers. We’ll come across some other values soon.

      + +

      Comments

      + +

      In ruby, any part of a line that comes after a # is ignored. This is useful when you’re writing complicated programs, as it allows you to write human-readable comments to document your code.

      +
      001: > 2 + 2  # add together 2 and 2
      + => 4 
      +002: > # this does nothing
      +003: > 
      +
      +

      Notice how in line 002 above there is no => and no return value; comments don’t evaluate to anything - they’re completely ignored.

      +
      Task: +
        +
      1. Pick a partner.
      2. + +
      3. Open irb on one of your laptops.
      4. + +
      5. For each of the following ruby expressions, try to agree what value you think they evaluate to. Check if you're right in irb.
      6. +
      +
      1 + 2
      +
      +5 - 6
      +
      +8 * 9
      +
      +6 / 2
      +
      +5 / 2
      +
      +5.0 / 2
      +
      +5 % 2
      +
      +2.even?
      +
      +3.even?
      +
      +"hello " + "world"
      +
      +"Bob" * 3
      +
      +"Bob" + 3
      +
      +"don't shout".upcase
      +
      +"edam".reverse
      +
      + +
      Task: +
        +
      1. +

        (Challenge for pairs who finish early). What does the operation ^ do? E.g.

        + +
         1 ^ 2
        +
        + 2 ^ 5
        +
        + 4 ^ 5
        +
      2. +
      +
      +
      + + +
      + + +

      Exercise summary

      + +

      Before we will move on to variables, we’ll quickly look at a few of the things that you found out in the previous exercise:

      +
      > 6 / 2
      +=> 3
      +> 5 / 2
      +=> 2
      +> 5.0 / 2
      +=> 2.5
      +> 5 % 2
      +=> 1
      +
      +

      If you give ruby integers (whole numbers), it will do integer division. For example, 5 / 2 gives 2 as it is the largest whole number of times you can remove 2 from 5. The partner to integer division is the remainder 5 % 2, giving 1. Together these two operations tell you that 2 goes twice into 5 with remainder 1. If you give ruby decimals it will do normal division. Everyone gets caught out by this at some point. You have been warned!

      +
      > 2.even?
      +=> true
      +
      +

      The line above is actually pretty special. We’ve just asked the value 2 a question and it’s responded. In programming terms, this works because 2 is an object - something that contains both data and methods that can query/manipulate the data. In this case, even? is the method that we called. In ruby all values are objects. This is unusual and isn’t true in many other programming languages. We’ll leave it at that for the time being, but you’ll learn more about this later.

      +
      > "hello " + "world"
      +=> "hello world"
      +> "don't shout".upcase
      +=> "DON'T SHOUT"
      +
      +

      Here you met another third type of value: "hello" is a string. As you see here, you can add strings together. Like all ruby values, strings are also objects and therefore have methods. Here we used the upcase method, to change the string into uppercase. You can find out more about the methods that strings have in the ruby docs.

      +
      > "Bob" + 3
      +TypeError: can't convert Fixnum into String
      +from (irb):1:in `+'
      +
      +

      Oh dear! Turns out that you can’t add a string to an integer. Have another read of the message that irb gave you. Can you figure out what it is saying? When something goes wrong, ruby tries to be as helpful as it can. Learning to interpret the errors that ruby gives is an important part of learning to become a programmer.

      + +

      The ^ operator in the optional challenge is bitwise exclusive or.

      + +
      + + +
      + + +

      Names & Variables

      + +

      So far we’ve used irb as a clever calculator, by working with values directly. Programming becomes a lot more powerful when you’re able to give values names.

      + +

      A name is just something that you can use to refer to a value. In ruby you create a name by using the assignment operator, =.

      +
      age = 5
      +
      + +age + +5 + + + + + + + + + +

      You can change the value associated with a name at any point. It doesn’t even have to be the same type of value as the first value assigned to the name. Here we change the value associated with age to a string:

      +
      age = "almost three"
      +
      + +age +“almost three” + + + + + + + + + + +

      Types of name

      + +

      There are various different types of name in ruby:

      + +
        +
      • local variables e.g. age: Local variables begin with a lower-case letter. They’re all we’ll be using for now.
      • + +
      • constants e.g. PI: Any name that starts with a capital letter is deemed to be a constant. Ruby will complain if you try to change its value at a later date.
      • + +
      • instance variables e.g. @name: Instance variables start with a single @ sign. They’re used to store values inside objects. More later.
      • + +
      • class variables e.g. @@count: Class variables start with two @@ signs. They’re used to store values relevant to a set of objects. More on this later too.
      • + +
      • global variables e.g. $last_error: Global variables start with a $ sign. They’re available anywhere in your program. Relying on global variables is normally a bad idea.
      • +
      + +

      For the moment, we will just be using local variables. The important thing to take from the above tables is that local variables must start with a lower-case letter.

      + +

      String interpolation

      + +

      String interpolation is a way of taking a variable and putting it inside a string.

      + +

      To write a string in ruby you can either use ' or ".

      +
      string1 = 'hello'
      +string2 = "hello"
      +
      +

      In the code above, string1 and string2 are exactly the same. The difference between ' and " is that " allows you to do string interpolation:

      +
      age = 5
      +age_description = "My age is #{age}."
      +=> "My age is 5."
      +
      +

      Any ruby expression inside the #{ } will be evaluated and inserted into the string. Here we gave it the variable age, which points to the value 5. As 5 is a value it evaluates to itself, so 5 is inserted into the string.

      +
      Task: + +
        +
      1. With your partner, decide what each of the following instructions will do. Test to see if you're right in irb.
      2. +
      + + + +
      a = 1
      +
      +a
      +
      +a+1
      +
      +a
      +
      +a = a + 1
      +
      +a
      +
      +b = "hello"
      +
      +b
      +
      +c = b.capitalize
      +
      +b
      +
      +c
      +
      +d = "hello"
      +
      +e = d.capitalize!
      +
      +d
      +
      +e
      +
      +name = "Dave"
      +
      +f = "Hello #{name}! "
      +
      +f
      +
      +name = "Sarah"
      +
      +f
      +
      +f * 5
      +
      + + +
      Task: +
        +
      1. (Extension for pairs who finish early.)[Note: this exercise has a lot more to do with maths than programming. If you dont get it dont worry!] +

        Consider the expression + x = (2 + 5*x - x**2)/5 +

        + +
          +
        1. Let x = 1.1
        2. + +
        3. Write x = (2 + 5*x - x**2)/5 and then evaluate this multiple times (using the up arrow in irb)
        4. + +
        5. What happens? Can you explain why?
        6. + +
        7. Let x = 1 and do the same thing. What happens and why?
        8. +
        +
      2. +
      +
      +
      + + +
      + + +

      Exercise summary

      +
      > x = 1
      +=> 1
      +> x = x + 1
      +=> 2
      +
      +

      This might seem really obvious, but it’s worth pointing out: = is an assignment operator; it means ‘set name on the left equal to the value on the right’. It isn’t the same equals as you see in maths! In maths x = x + 1 doesn’t really make sense -it’s an equation with no (finite) solutions. In ruby x = x + 1 makes perfect sense - just set x to be one more than it was before.

      +
      b = "hello"
      +c = b.capitalize
      +
      +b #=> "hello"
      +c #=> "Hello"
      +
      +d = "hello" 
      +e = d.capitalize!
      +
      +d #=> "Hello"
      +e #=> "Hello"
      +
      +

      This example is pretty important. In the first case capitalize gives back “HELLO”, but leaves the original string untouched.

      + + +b +“hello” + + + + + + + + + +c +“Hello” + + + + + + + + + + + +

      In the second case, we use the in-place version of captialize!. It changes the actual string that d is pointing to, and sets e to point there too. In ruby, methods often come in two flavours like this, with the ! version modifying the original object in place. You could also try out reverse/reverse! and upcase/upcase!.

      + + + + + + + + + + + + + + + + + + +d + +e +“Hello” + +
      > name = "Dave"
      +=> "Dave"
      +> f = "Hello #{name}! "
      +=> "Hello Dave! "
      +> f
      +=> "Hello Dave! "
      +> name = "Sarah"
      +=> "Sarah"
      +> f
      +=> "Hello Dave! "
      +
      +

      The above shows that string interpolation happens when you write it down. When you first write f = "Hello #{name}! " ruby immediately looks up name and bakes it straight into the string. Setting name to something differeny later on, won’t change this.

      + +

      In the extra challenge, the expression gave an iterative approximation to sqrt(2). You can tell by rearranging and solving the equation, that any fixed point must be a sqrt of 2. In the final part, by giving it x=1 you forced ruby to do integer arithmetic. If you're into that sort of thing, you might like to try and find the fixed points in this case!

      + +
      + + +
      + + +

      Introducing sinatra

      + +

      Sinatra is a lightweight web framework written in ruby.

      + +

      Getting sinatra

      + +

      You can install sinatra on your laptop using rubygems - ruby’s excellent package manager. When people write their own ruby libraries, they usually release them as a gem, so that others can quickly and easily install them. Sinatra is one of these libraries. To install it do:

      + +
      $ gem install sinatra
      + +

      at the command line. We will also need a few other rubygems, so install these too:

      + +
      $ gem install rack-test
      +
      Task: +
        +
      1. +

        Install sinatra: at the command line run

        + +
         $ gem install sinatra
        + $ gem install rack-test
        +
      2. + +
      3. +

        Download the code for the session:

        + +
         $ git clone https://github.com/code61/sinatra_c3s1.git
        +
      4. +
      +
      +

      A simple ruby application

      + +

      So far, we’ve only used ruby in irb. If we’re going to write ruby applications, we need to go beyond this. In this section, we’re going to have some code written in a file (a .rb file) and we’re going to run the whole file through the interpreter, using the ruby command.

      + +

      We’re now going to look at a very simple ruby web application that uses sinatra.

      +
      # in app.rb:
      +
      +require 'sinatra'
      +
      +get '/' do
      +    "hello"
      +end
      +
      +

      This file is very simple. The first line imports the sinatra library - this is what does most of the work here. The next bit tells sinatra how to respond to a certain type of request. In particular it says that if it receives a GET request to the root url it should send back the text “hello”.

      + +

      To run this app you need to run the app.rb file using ruby.

      + +
      $ cd sinatra_c3s1
      +$ ruby app.rb
      +== Sinatra/1.3.3 has taken the stage on 4567 for development with backup from Thin
      +>> Thin web server (v1.3.1 codename Triple Espresso)
      +>> Maximum connections set to 1024
      +>> Listening on 0.0.0.0:4567, CTRL+C to stop
      + +

      Sinatra has started a webserver on your computer, which you can view in your browser. It will be displayed at the IP address 0.0.0.0 on port 4567. 0.0.0.0 always points to the machine you are currently using. Another way of saying this is to use the word localhost. You will be able to view the site by typing one of the following into your browser address bar:

      + +
        +
      • 0.0.0.0:4567
      • + +
      • localhost:4567
      • +
      + +

      Changing the app

      + +

      What just happened involved quite a lot of magic. Because of the line require sinatra, when you ran the file through ruby, the following happened:

      + +
        +
      1. Sinatra started a webserver on your computer.
      2. + +
      3. It used the code in your file to tell the webserver how to respond to a certain type of request.
      4. + +
      5. The webserver sat on your computer, waiting for you to send it a request from your browser.
      6. +
      + +

      Right now, you don’t really need to understand how all this works. You just need to be able to understand the general overview and how to change certain bits.

      + +

      We’re now going to change part of the app, so that the webserver says something different.

      + +

      There are two steps to this:

      + +
        +
      1. Make a change in app.rb.
      2. + +
      3. Restart the server, so it knows about the change you made. To do this, you need to first kill the server, using Ctrl-c in the terminal, and then restart it using ruby app.rb.
      4. +
      +
      Task: +
        +
      1. +

        Run the app. In the sinatra_c3s1 directory:

        + +
         $ ruby app.rb
        + +

        Check you can see the page in your webbrowser at localhost:4567.

        +
      2. + +
      3. +

        Make a change to app.rb so that it instead says "Hello there!". Check you can see the change in your browser (you will have to stop the server with Crtl-C then restart it again with ruby app.rb).

        +
      4. + +
      5. +

        Try visiting a different url (e.g. localhost:4567/about). What happens?

        +
      6. + +
      7. +

        (Extension for those who finish early.) Have a look in the file test1.rb. What do you think the test_default at the end of the file does? Try running the test file from the command line:

        + +
         $ ruby test1.rb
        + +

        If the test passes, change the code back to see what happens when it fails. If it fails, try and make it pass!

        +
      8. +
      +
      +
      + + +
      + + +

      Basic app

      + +

      Taking parameters from the url

      + +

      Take a look at the following code:

      +
      # in app.rb:
      +
      +require 'sinatra'
      +
      +get '/' do
      +    "hello"
      +end
      +
      +get '/:name' do
      +    name = params[:name]
      +    name
      +end
      +
      +

      The /:name is a URL matcher. It will match / followed by any word, for example /tom, /gertrude or /this_isnt_a_name. Sinatra will make this value available in something called the ‘params hash’. You don’t need to worry about this at the moment. The first line of the block, pulls the value out of the params hash and sets it to the local variable name.

      +
      Task: +
        +
      1. Open app.rb in Sublime text and uncomment the code at the bottom.
      2. + +
      3. Change it so that visiting localhost:4567/tom shows "Hello Tom!" in the browser (and similarly for other names). [You will need to use string interpolation and a string method.]
      4. + +
      5. (Extension.) Check your result by running ruby test2.rb in the console.
      6. + +
      7. See if you can make it so that localhost:4567/tom/bye shows "Goodbye Tom" in the browser (and similarly for other names).
      8. + +
      9. (Extension - hard.) See if you can write another test in test2.rb to test your result.
      10. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish the exercises from class.
      2. + +
      3. Do the Codecademy Ruby track Sections 1 and 2.
      4. + +
      5. Get a Heroku account and upload an ssh key (see below).
      6. +
      +
      +

      About Heroku

      + +

      Heroku is a cloud-based web hosting solution, specifically designed for hosting web applications. It started out as a Rails host, but has since branched out into other frameworks (e.g. Sinatra, Node.js) and languages (e.g. Java, Python).

      + +

      They aim to completely manage your apps online infrastructure: you provide them with the code, they set it up and run it online. If you have a lot of users and want to scale your app up, they make it easy to allocate more resources so you can handle the increased traffic (for a price!).

      + +

      Setting up an account

      + +

      Before you deploy your app to heroku you need to create an account.

      +
      Task: +
        +
      1. Sign up for an account at Heroku.
      2. + +
      3. After you log in, download and install the heroku toolbelt. (This will allow you to interact with heroku from the command line).
      4. +
      +
      +

       Setting up ssh with heroku

      + +

      The final part of the set up is to upload your ssh keys to Heroku. You might remember about ssh keys from the initial installation instructions: they’re basically a way of identifying yourself to a server without typing in your password each time.

      + +

      The heroku toolbelt makes this very easy. On the command line (in any folder) type:

      + +
      $ heroku keys:add
      + +

      You can check it worked by typing:

      + +
      $ heroku keys
      + +

      It should list the ssh key that you just added.

      +
      Task: +

      Upload your ssh key to heroku by running

      + +
      $ heroku keys:add
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c3s2/index.html b/c3s2/index.html new file mode 100644 index 0000000..b28815a --- /dev/null +++ b/c3s2/index.html @@ -0,0 +1,555 @@ + + + + + + Introduction to Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      If statements and comparisons

      + +

      So far we’ve just used ruby to evaluate simple expressions. Coding becomes a lot more interesting when you can use your code for simple logic tasks:

      +
      if age >= 18
      +  "Here's the vodka you wanted."
      +else
      +  "Move along please."
      +end
      +
      +

      The code within the if block will only be run if the statement is true. If the statement is false, the code in the else block will be run instead.

      + +

      Comparisons

      + +

      There are some basic comparisons that will be useful when using if statments

      + + + + + + +
      SymbolMeaning
      ==Is equal to
      >Greater than
      <Less than
      >=Greater than or equal to
      <=Less than or equal to
      !=Not equal to
      +

      Comparisons evaluate to true or false.

      +
      Task: + +

      Working with a partner, try out each of these comparisons in irb:

      + + +
      4 == 5
      +
      +'five'.length > 5
      +
      +a = 20
      +a <= 20
      +
      +true >= false
      +
      +'aardvark' < 'anteater'
      +
      +'we' != 'done yet'
      +
      + +
      +
      + + +
      + + +

      Post requests revisited

      + +

      Last time we looked at responding to get requests:

      +
      get '/' do
      +  "Hello there!"
      +end
      +
      +

      As you know from the Introduction to Web Programming course, GET is only one of several types of web requests. Another is the POST request, which is commonly used for submitting data from a web form.

      + +

      Suppose we have the following HTML form:

      +
      <form method="post" action='/'>
      +    <input type='text' name='user_name'>
      +    <input type='text' name='user_age'>
      +
      +    <input type='submit'>
      +</form>
      +
      +

      The form will submit via a POST request to the root url, /. We can respond to this using the following sinatra block:

      +
      post '/' do
      +  name = params[:user_name]
      +  age  = params[:user_age]
      +
      +  "Hello #{name}. You are #{age} years old."
      +end
      +
      +

      Note that, like the words matched in the url, the value of the user_name field is made available in the params hash. (If you want to have a look at the params hash you could put a raise params.inspect at the beginning of the method.)

      +
      Task: +
        +
      1. Fork the repository https://github.com/code61/sinatra_c3s2 (using the fork button on the top right of the repository page on github).
      2. + +
      3. Clone down your fork of the repository onto your laptop.
      4. + +
      5. Open the sinatra_c3s2 project in Sublime Text and have a read through app.rb. See if you can predict what the app will do.
      6. + +
      7. Run the app from the command line (ruby app.rb), to see if you were right.
      8. + +
      9. (Optional) Add the line raise params.inspect right at the top of the post block. Restart the app and see what happens. When you've had a look, make sure you remove the line again!
      10. +
      +
      +
      + + +
      + + +

      App deployment

      + +

      We’re now going to look at how to get the Sinatra app online, a process known as deployment. We’re going to deploy the app to Heroku, which offers easy hosting for a variety of web frameworks - all you need to do is push up a git repository, and they take care of everything else!

      + +

      You should have set up a heroku account and uploaded your ssh keys for homework.

      + +

      Preparation

      + +

      There are a few files sinatra_c3s2 that we need if we’re going to deploy the app to heroku:

      + +
        +
      • config.ru
      • + +
      • Gemfile
      • +
      + +

      config.ru contains the lines

      +
      require './app.rb'
      +run Sinatra::Application
      +
      +

      These lines are to tell Heroku which file to find your application (app.rb) and how to run it (using Sinatra).

      + +

      The Gemfile is a way of specifying which gems your project uses. Heroku needs to know this so it knows which libraries it needs to run your app. The Gemfile is also really helpful way of remembering yourself which gems you need and is invaluable when working with others.

      +
      # Gemfile
      +
      +source 'https://rubygems.org'
      +
      +gem 'sinatra'
      +
      +

      Along with rubygems, ruby has a tool called bundler. Bundler helps you manage your ruby gems. If you run bundle install it will look in the Gemfile and install any gems that you don’t already have.

      + +
      $ bundle install
      + +

      will also create a Gemfile.lock which specifies the exact version of the gems (e.g. the sinatra library) that you are using. This means that heroku (and anyone else you’re collaborating with using git) now knows exactly which gems you are using and can pick to use the same versions. You need to check this in to your repository:

      + +
      $ git add --all
      +$ git commit -m "Added Gemfile.lock"
      + +

      Deploying to Heroku

      + +

      Once your app is prepared, the first thing you need to do is create a new empty heroku application. To do this you use the heroku create command:

      + +
      $ heroku create
      +Creating arcane-gorge-2129... done, stack is cedar
      +http://arcane-gorge-2129.herokuapp.com/ | git@heroku.com:arcane-gorge-2129.git
      +Git remote heroku added
      + +

      You’ll see that it created an app for you. In my case the app is called arcane-gorge-2129 and can be found at http://arcane-gorge-2129.herokuapp.com. It also added a git remote for you.

      + +
      $ git remote -v
      +heroku  git@heroku.com:arcane-gorge-2129.git (fetch)
      +heroku  git@heroku.com:arcane-gorge-2129.git (push)
      +origin  git@github.com:code61/sinatra_project_1.git (fetch)
      +origin  git@github.com:code61/sinatra_project_1.git (push)
      + +

      Deploying

      + +

      You deploy your repository by pushing to this remote. Heroku will serve whatever is in the master branch. Here we push the master branch up to the heroku remote:

      + +
      $ git push heroku master
      +Counting objects: 11, done.
      +Delta compression using up to 2 threads.
      +Compressing objects: 100% (6/6), done.
      +Writing objects: 100% (11/11), 1.08 KiB, done.
      +Total 11 (delta 1), reused 0 (delta 0)
      +
      +-----> Ruby/Rack app detected
      +-----> Using Ruby version: ruby-1.9.3
      +-----> Installing dependencies using Bundler version 1.3.2
      +       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin --deployment
      +       Fetching gem metadata from https://rubygems.org/..........
      +       Fetching gem metadata from https://rubygems.org/..
      +       Installing rack (1.5.2)
      +       Installing rack-protection (1.5.0)
      +       Installing tilt (1.4.1)
      +       Installing sinatra (1.4.3)
      +       Using bundler (1.3.2)
      +       Your bundle is complete! It was installed into ./vendor/bundle
      +       Cleaning up the bundler cache.
      +-----> Discovering process types
      +       Procfile declares types     -> (none)
      +       Default types for Ruby/Rack -> console, rake, web
      +
      +-----> Compiled slug size: 25.0MB
      +-----> Launching... done, v3
      +       http://arcane-gorge-2129.herokuapp.com deployed to Heroku
      +
      +To git@heroku.com:arcane-gorge-2129.git
      + * [new branch]      master -> master
      + +

      After you push, heroku automatically updates the app and launches it for you. You can now see the app by visiting the url (in this case http://arcane-gorge-2129.herokuapp.com).

      +
      Task: +

      Deploy your sinatra_c3s2 app to Heroku:

      + +
        +
      1. +

        Install your bundle to get a Gemfile.lock. In your sintara_c3s2 directory run:

        + +
         $ bundle install
        +
      2. + +
      3. +

        Add your work (and new Gemfile.lock) to your repository:

        + +
         $ git add --all
        + $ git commit -m &#39;Added Gemfile.lock&#39;
        +
      4. + +
      5. +

        Create a new heroku app:

        + +
         $ heroku create
        +
      6. + +
      7. +

        Push your work to Heroku

        + +
         $ git push heroku master
        + +

        (for subsequent updates you should be ok with just git push heroku).

        +
      8. + +
      9. +

        Visit the url that heroku provide, to check that your app is running!

        +
      10. +
      +
      +
      + + +
      + + +

      HTML templates

      + +

      So far we’ve just returned text to the browser. It would be better if we could return proper HTML pages. We can do this by using HTML templates.

      +
      # in app.rb
      +
      +require 'sinatra'
      +
      +get '/' do
      +  erb :form
      +end
      +
      <!-- in views/form.erb -->
      +
      +<!DOCTYPE html>
      +<html>
      +<head>
      +  <title>Barman 2.0</title>
      +</head>
      +<body>
      +  <div class='container'>
      +    <form method="post" action='/'>
      +      <input type='text' name='user_name' placeholder='name'>
      +      <input type='text' name='user_age' placeholder='age'>
      +
      +      <button type='submit'>Submit</button>
      +    </form>
      +  </div>
      +</body>
      +</html>
      +
      +

      The line erb :form tells sinatra to look for a file called form.erb in a folder called views. It then processes that file using the erb (embedded ruby) templating language and returns the result to the user.

      + +

      The form.erb above isn’t very interesting: it is just a static template and doesn’t have any ruby embedded in it. Let’s look at a slightly better example:

      +
      # in app.rb
      +
      +get '/' do
      +  erb :form
      +
      +post '/' do
      +  @name = params[:user_name]
      +  @age  = params[:user_age]
      +
      +  erb :welcome
      +end
      +
      <!-- in views/welcome.erb  -->
      +
      +<!DOCTYPE html>
      +<html>
      +<head>
      +    <title>hello</title>
      +</head>
      +<body>
      +    <h1>Hello <%= @name %>. You are <%= @age %> years old.</h1>
      +</body>
      +</html>
      +
      +

      The important bits are:

      + +
        +
      • In app.rb we assign params[:name] to a special type of variable @name. The special type of variable is an instance variable which has to begin with a single @.
      • + +
      • We use the instance variable in the views/greet.erb inside a special erb tag <%= ... %>. The erb templater looks for these tags and interprets the inside as ruby.
      • +
      + +

      Sinatra emphasises convention over configuration: rather than specifying the exact place to find the template, you just give the name and Sinatra ‘knows’ where to look. This means you have to write less code in the long run, but also that you have to know the conventions before you start.

      +
      +
      +

      Sinatra template summary

      +
      +
      +
        +
      1. You call a template with the line erb :template_name.
      2. +
      3. For this to work, you will need a template called template_name.erb in the views folder.
      4. +
      5. Instance variables (ones that start with @) will be shared with the template.
      6. +
      7. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable >
      8. +
      +
      +
      Task: +
        +
      1. +

        Uncomment the bottom part of sinatra_c3s2/app.rb and comment out the top two blocks.

        +
      2. + +
      3. +

        Restart your server and check you can see the new page h1 sections.

        +
      4. + +
      5. +

        Add twitter bootstrap to your templates, linking to the online hosted version as described on the Bootstrap CDN section of the bootstrap docs.

        +
      6. + +
      7. +

        Add a div class=&#39;container&#39; around the page content, and add some styling to the form (see here).

        +
      8. + +
      9. +

        Add and commit your changes to your local git repo.

        +
      10. + +
      11. +

        Deploy your changes:

        + +
         git push heroku
        +
      12. +
      +
      +
      + + +
      + + +

      Logical operations

      + +

      It’s often useful to combine various conditions:

      +
      if age < 12 || height < 1.2
      +	"You are allowed on the ride."
      +else
      +	 "Try a different helter-skelter. There's nothing for you here."
      +end
      +
      +

      In the above snippet of code, the || means OR. If the person is under 12 or is smaller than 1.2m they are allowed on the ride.

      + +

      Logical operations

      + +

      Ruby has three ways of combining conditions:

      + +

      and (&&)

      + +

      If you use an && the output is true only if both inputs are true. You can write this in terms of a truth table:

      +
      false && false #=> false
      +false && true  #=> false
      +true  && false #=> false
      +true  && true  #=> true
      +
      +

      or (||)

      + +

      If you use the || the output is true if at least one of the inputs is true. || means one or the other or both:

      +
      false || false #=> false
      +false || true  #=> true
      +true  || false #=> true
      +true  || true  #=> true
      +
      +

      not (!)

      + +

      The ! is not. It is a quick way of reversing the truth of the condition:

      +
      !false #=> true
      +!true  #=> false
      +
      Task: + +
        +
      1. Working with a partner, see if you can guess what the following expressions evaluate to. Test in irb to see if you're right.
      2. +
      + + +
      1 > 2 && 3 > 4
      +
      +1==1 || 10 ==9
      +
      +!(5<6)
      +
      +(1<=2 && 3>4) || (3 <= 4 && "ham")
      +
      + +
      +
      + + +
      + + +

      Truthy and falsey

      + +

      In the last exercise you found out something interesting:

      +
      true && "ham" #=> "ham"
      +
      +

      Which is a bit weird. There are actually two things going on here:

      + +
        +
      1. The string ham is considered to be true
      2. + +
      3. The overall statement evaluates to the last expression in it
      4. +
      + +

      Truthy and falsey

      + +

      In ruby there are only two values that are considered false: false and nil. We say that false and nil are falsey.

      + +

      Everything else is considered to be true. We say that all other objects are truthy.

      + +

      What we mean by ‘considered to be true’ is that if that value is used as a conditional in an if statement then the if code runs:

      +
      if 5
      +	x = 1
      +else
      +	x = 2
      +end
      +
      +x #=> 1
      +
      +

      In the above block of code, as 5 is truthy, the variable x is set to 1.

      +
      Task: +

      The bar is trialling a new initiative: Tuesdays is ladies night at the pub - no men allowed and all drinks are 2-4-1! They want you to update Bouncer 2.0 appropriately.

      + +
        +
      1. Add select boxes for sex and day on the form.
      2. + +
      3. Add new templates to be shown on ladies night to (a) turn away a customer if he is male (b) give them an extra drink if they are female.
      4. + +
      5. Add the required logic to app.rb to make it all work.
      6. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish the final exercise from class. Spend a bit of time trying to make the app look more presentable and 'bouncer-like'.
      2. + +
      3. Do the Codecademy Ruby track Sections 3 and 4.
      4. +
      +
      +

      Extension

      +
      Task: +

      Change your sinatra app into something more interesting:

      + +
        +
      • Add more options to the form.
      • + +
      • Make the logic in the views more complicated, so that you're using a few boolean operations.
      • + +
      • Change your app into a horoscope provider/career adviser/which-star-wars-character-are-you machine.
      • + +
      • Make it look nice, deploy it and show your friends.
      • +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c3s3/index.html b/c3s3/index.html new file mode 100644 index 0000000..63b54ba --- /dev/null +++ b/c3s3/index.html @@ -0,0 +1,504 @@ + + + + + + Introduction to Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Arrays

      + +

      An array is a way of storing a list of objects. Unlike in some other languages in ruby you don’t need to specify which sort of object the array will hold - it can even hold objects of different types.

      + +

      Arrays are written with square brackets.

      +
      my_array = [1,2,3]
      +
      +empty_array = []    # an array with no elements
      +
      Task: + +

      Working with a partner, guess what each of the following expressions will give, then try them out in irb:

      + + + +
      a = [3, 39, 1, 0, 5]
      +
      +a[1]
      +a.first
      +a[0]
      +a[5]
      +
      +a[-1]
      +a[-5]
      +a.last
      +
      +a[1..3]
      +a[1..-1]
      +
      +b = []
      +
      +a.empty?
      +b.empty?
      +a.length
      +b.length
      +
      +a.include?(39)
      +a.include?(49)
      +
      +a.reverse
      +a   # has this changed a?
      +a.reverse!
      +a   # has this changed a?
      +
      +a.sort
      +a   # has this changed a?
      +a.sort!
      +a   # has this changed a?
      +
      +a = [1, 2, 3, 4, 5]
      +
      +a[3] = 6
      +a   # What is a now?
      +
      +a[7] = 7
      +a   # What else has been added?
      +
      +a << 9  # This one's important - you'll see it a lot
      +
      + +
      +
      + + +
      + + +

      Exercise summary

      + +

      Here are some things you learnt in the last exercise:

      + +

      Accessing elements

      + +
        +
      • Arrays start from 0, so that the first elements is a[0]
      • + +
      • Arrays also allow indexing from the back, giving the last element as a[-1]
      • + +
      • If try to access beyond the end of the array it gives nil (instead of an error in other languages)
      • + +
      • You can access multiple elements by specifying a range, e.g. a[1..-1] is everything but the first element
      • +
      + +

      Array methods

      + +

      Arrays have many useful (and largely self-explanatory) methods, including:

      + +
        +
      • empty? - does the array have any elements, or is it the empty array []
      • + +
      • length
      • + +
      • include?(x) - is x in the array
      • + +
      • reverse, reverse! - as with strings the ! permanenty changes the array
      • +
      + +

       Adding to an array

      + +
        +
      • +

        You can add to an array by setting a given element explicitly a[5] = 6

        +
      • + +
      • +

        If the array isn’t long enough the gaps are filled with nil:

        + +
        a = [1, 2]
        +a[6] = 5
        +a #=> [1, 2, nil, nil, nil, nil, 5]
        +
      • + +
      • +

        You can also add to the end of an array by doing a << 5. This is very ‘rubyish’ and you’ll see it a lot.

        +
      • +
      + +
      + + +
      + + +

      Iteration

      + +

      Most programming language have some way of looping, or iterating, over a range of values.

      + +

      Ruby’s approach to this is slightly unusual - instead of you taking elements from the array one-by-one, the ruby array gives the elements to you one-by-one. This might seem like a small distinction to make, but it has a significant effect on the feel of the ruby language and how you think about coding with it.

      + +

      The way you get an array to give you its elements is by calling its each method:

      +
      array = [1, 2, 3, 4, 5]
      +sum   = 0
      +
      +array.each do |n|
      +  sum = sum + n
      +end
      +
      +sum #=> 15
      +
      +

      The each method accepts a block - in the example above, this is everything between do ... end.

      + +
        +
      • The each method sends the elements of the array one-by-one to the block.
      • + +
      • When the element arrives it is assigned to the variable n.
      • + +
      • The code on the inside of the block is then run.
      • +
      + +

      In the example above, each element is added to the sum. The example shows one method that you can use to sum the values in an array.

      + +

      Below is another example, which iterates over the elements of an array, separating them into one of two lists:

      +
      all_words   = ['hello', 'how', 'are', 'you', 'today']
      +long_words  = []
      +short_words = []
      +
      +all_words.each do |word|
      +  if word.length >= 5
      +    long_words  << word
      +  else
      +    short_words << word
      +  end
      +end
      +
      +long_words  #=> ['hello', 'today']
      +short_words #=> ['how', 'are', 'you']
      +
      +

      Please note: the summing and categorising examples above can be made much neater with the use of the array methods inject and select. We'll leave that for another day though

      +
      Task: + +

      Take another look through the code examples above. Check you really understand how they work. Try them out in irb, to check they work as advertised!

      + +
      +
      + + +
      + + +

      Lists of data

      + +

      So far we have only inserted single values and words into an already existing erb template. We will now look at using ruby to generate more of the template dynamically.

      + +

      Suppose you have a ruby array that you want to turn into an html list:

      +
      # in app.rb
      +
      +get '/fruit' do
      +  @fruits = ["Bananas", "Apples", "Raspberries"]
      +  erb :fruits_view
      +end
      +
      +

      We can do this by using the @fruits array’s each method to iterate over the elements and put them into the page one-by-one.

      +
      <!-- in views/fruits_view.erb -->
      +<ul>
      +  <% @fruits.each do |fruit| %>
      +    <li><%= fruit %></li>
      +  <% end %>
      +</ul>
      +
      +

      You might notice that we’ve used a different type of erb tag for the do ... end block: <% %> instead of <%= %>. This is really important:

      + +
        +
      • You need to use <%= %> if you want the result of executing that line of ruby to be added to the page.
      • + +
      • You need to use <% %> if you don’t want the result of executing that line of ruby to be added to the page.
      • +
      + +

      Here, the bits we want adding are the elements of the array, so only they have the <%= %> tags. The code will cause the following html to be generated:

      +
      <ul>
      +  <li>Bananas</li>
      +  <li>Apples</li>
      +  <li>Raspberries</li>
      +</ul>
      +
      +

      You can also use the same technique to generate tables and other html (lists of divs etc.).

      +
      Task: +
        +
      1. Fork, then clone the code for this exercise https://github.com/code61/sinatra_c3s3.
      2. + +
      3. Add code to the body of todo.erb, so that the @todos display as an ordered list.
      4. + +
      5. Add, commit and push your code to Github.
      6. + +
      7. Add code to the body of schedule.erb, so that the items in the @schedule display as rows in a table. Note that @schedule is an array of arrays - you'll need to iterate over the first array, and within the loop use the normal ways of accessing elements of an array pull out the items.
      8. + +
      9. Add, commit and push your code to Github.
      10. + +
      11. Take a look at the get &#39;/rsvps&#39; block. Try the CSV.read bit in irb, to see what it does. Have a go at writing the code to categorise rsvps into acceptances/rejections and count them.
      12. + +
      13. Update the rsvps.erb view, so that the right information is displayed.
      14. + +
      15. Add, commit and push your code to Github.
      16. +
      +
      +
      + + +
      + + +

      Sinatra static assets

      + +

      Last week we linked Twitter Bootstrap into your view templates, by linking to the online hosted version <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">. What if we want to link to our own files?

      + +

      When we were building static sites, this was simple: we just created a main.css file in our site folder, and linked to it. The problem is that a sinatra site folder is not like a static site folder. We’ve already seen this: app.rb controls the url structure, not the folders in the app folder. (Just try going to ‘/app.rb’ or ‘/views/index.erb’). Because of this, just dropping a main.css into the sinatra folder and trying to link to it won’t work.

      + +

      Thankfully sinatra has a solution to this problem: if you create a folder called public, any files you put in there will be available from the root url. For example, if I have a file public/main.css, I can then link to this from my template files using <link rel="stylesheet" href="/main.css">. The two important things to note here are:

      + +
        +
      1. I’m using a root-relative link (starting with a /). If you don’t do this, you’ll have problems if you ever call that template from a different url route.
      2. + +
      3. I’m linking directly to main.css, not to public/main.css.
      4. +
      +
      +
      +

      Sinatra conventions

      +
      +
      +
        +
      1. Files inside the public folder will be served at the root of the site. This is where you should put your own stylesheets/images etc.
      2. +
      3. You call a template with the line erb :template_name.
      4. +
      5. For this to work, you will need a template called template_name.erb in the views folder.
      6. +
      7. Instance variables (ones that start with @) will be shared with the template.
      8. +
      9. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable >
      10. +
      +
      +
      Task: + +
        +
      1. Link the bootstrap stylesheet you'll find in public/dist/css/bootstrap.css into the head of todo.erb and schedule.erb.
      2. +
      + +
      +
      + + +
      + + +

      Sinatra layouts

      + +

      One of the most important principles in software engineering is to stay DRY: don’t repeat yourself.

      + +

      The basic idea is that you don’t want to be copying and pasting the same code into multiple places. If you’re doing this, you’re making a lot of work for yourself should you ever decide to change that code.

      + +

      One way of staying DRY that we’ll meet soon is writing functions: if there’s a task that you do repeatedly, write a function to put the logic for that task in one place and then call the function when you need to do the task.

      + +

      Another way, that we’ll be looking at today, is in the form of layouts.

      + +

      The Problem

      + +

      In the exercise today, you’ve been using a lot of erb view templates. You have 4 different templates, which all share the same basic outline:

      +
      <!-- in views/index.erb -->
      +<!DOCTYPE html>
      +<html>
      +<head>
      +  <title>Event Manager 2.0</title>
      +</head>
      +<body>
      +
      +  <h1>Picture Unveiling Evening - Event Managment</h1>
      +
      +  <ul>
      +    <li><a href='/todos'>Todo list</a></li>
      +    <li><a href='/schedule'>Event schedule</a></li>
      +    <li><a href='/rsvps'>RSVPs</a></li>
      +  </ul>
      +
      +</body>
      +</html>
      +
      <!-- in views/todo.erb -->
      +<!DOCTYPE html>
      +<html>
      +<head>
      +  <title>Event Manager 2.0</title>
      +</head>
      +<body>
      +  <h1>Todo list</h1>
      +
      +  <ul>
      +    <% @todos.each do |todo| %>
      +      <li><%= todo %></li>
      +    <% end %>
      +  </ul>
      +
      +</body>
      +</html>
      +
      +

      These files are almost the same - a lot of copy and paste has gone on.

      + +

       The solution

      + +

      Sinatra gets round this problem by allowing you to have a layout.erb file in your views folder:

      +
      <!-- views/layout.erb -->
      +<!DOCTYPE html>
      +<html>
      +<head>
      +  <title>Event Manager 2.0</title>
      +</head>
      +<body>
      +
      +  <%= yield %>
      +
      +</body>
      +</html>
      +
      +

      You can then write only the bits that change in the other two views:

      +
      <!-- in views/index.erb -->
      +<h1>Picture Unveiling Evening - Event Managment</h1>
      +
      +<ul>
      +  <li><a href='/todos'>Todo list</a></li>
      +  <li><a href='/schedule'>Event schedule</a></li>
      +  <li><a href='/rsvps'>RSVPs</a></li>
      +</ul>
      +
      <!-- in views/todo.erb -->
      +<h1>Todo list</h1>
      +
      +<ul>
      +  <% @todos.each do |todo| %>
      +    <li><%= todo %></li>
      +  <% end %>
      +</ul>
      +
      +

      Sinatra knows that if you have a file called layout.erb it should use that as a layout. If you call erb :index:

      + +
        +
      • It takes the layout.erb file.
      • + +
      • It finds the bit where it says <%= yield %>.
      • + +
      • It inserts index.erb at that point.
      • +
      + +

      You can find more about Sinatra layouts on the internet.

      +
      +
      +

      Sinatra conventions

      +
      +
      +
        +
      1. If you have a file views/layout.erb Sinatra will treat it as a layout file: whenever it renders another template, it will try and insert the output into the <%= yield %> part of the layout file.
      2. +
      3. Files inside the public folder will be served at the root of the site. This is where you should put your own stylesheets/images etc.
      4. +
      5. You call a template with the line erb :template_name.
      6. +
      7. For this to work, you will need a template called template_name.erb in the views folder.
      8. +
      9. Instance variables (ones that start with @) will be shared with the template.
      10. +
      11. You use these shared instance variables in the template by putting them inside an erb tag: <%= @my_variable %>
      12. +
      +
      +
      Task: +

      Refactor your views:

      + +
        +
      1. Create a layout file, containing the shared material from each view.
      2. + +
      3. Remove the shared material from each view.
      4. + +
      5. Check that the screens still look the same!
      6. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish the final exercise from class. If you have time, try and make the app look a bit nicer and practice deploying to heroku.
      2. + +
      3. Do the Codecademy Ruby track Sections 5 and 6.
      4. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c3s4/index.html b/c3s4/index.html new file mode 100644 index 0000000..db686a8 --- /dev/null +++ b/c3s4/index.html @@ -0,0 +1,556 @@ + + + + + + Introduction to Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Hashes

      + +

      A Hash is ruby’s basic key-value store: a place where you can store values, and look them up by a key. The Hash and the Array are ruby’s two common ways of storing a collection of objects. The key differences between ‘Hash’ and ‘Array’ are:

      + +
        +
      • In an Array objects are stored in order. You can think of an Array as a list.
      • + +
      • In an Array we reference objects by a numerical index.
      • + +
      • In a Hash there is no order on the objects. You can think of a Hash as a general collection.
      • + +
      • In a Hash objects are referenced by a key. The key can be a number or a word (or several other things).
      • +
      + +

      Here is an example of a simple hash:

      +
      character = {'name'=>'Bart', 'surname'=>'Simpson', 'age'=> 10, 'catchphrase' => 'Eat my shorts'}
      +
      +character['name'] #=> 'Bart'
      +character['catchphrase'] #=> 'Eat my shorts'
      +
      +

      In particular:

      + +
        +
      • You write a Hash using the curly brackets { }.
      • + +
      • Each element of the hash has a key e.g. 'name' and a value e.g. 'Bart'.
      • + +
      • When you write the hash you put the keys and values using the => symbol: key => value.
      • + +
      • To pull values out of a hash you put the key inside [ ].
      • +
      +
      Task: +
        +
      1. With your partner work through the expressions below. See if you can guess what each expression will do, then test by pasting into irb.
      2. + +
      3. If you finish early, have a look at the 'Arrays and back' extension tab.
      4. +
      +
      h = {'one' => 1, 'two' => 2, 'three' => 3}
      +
      +# Accessing elements
      +# ------------------
      +
      +h['one']
      +h['two']
      +h['four']
      +
      +# Setting elements
      +# ----------------
      +
      +h['five'] = 5
      +h['one'] = 1.0
      +h.delete('one')  # What does this return? Does it change the hash?
      +
      +# Some methods
      +# ------------
      +
      +h.length
      +h.empty?
      +h.keys
      +h.values
      +h.has_key?('one')
      +h.has_value?(7)
      +
      +# Iterating
      +# ---------
      +
      +h.each do |key, value|
      +  puts "#{key}: #{value}"
      +end
      +
      +
      +# Combining
      +# ---------
      +
      +h1 = {'a'=>1, 'b'=>2}
      +h2 = {'b'=>3, 'c'=>4}
      +
      +h1.merge(h2)
      +h1    # what has this done to h1?
      +h1.merge!(h2)
      +h1    # what is h1 now?
      +
      +
      +# Using a hash for counting (extension)
      +# -------------------------
      +
      +# start with an empty hash
      +h = {}
      +
      +['a', 'b', 'a', 'a'].each do |letter|
      +    if h.has_key?(letter)
      +        # if the letter is already in the hash, increase
      +        # its count by 1
      +        h[letter] += 1
      +    else # letter isn't in the hash
      +        # so put it in and set the count to 1
      +        h[letter] = 1
      +    end
      +end
      +
      +h   # what is h now?
      +
      +# A slicker way to count (extension)
      +# ----------------------------------
      +
      +# A slightly slicker way of doing this is
      +# using a hash with a default value:
      +
      +h = Hash.new(0) # 0 is the default value that is 
      +                # returned when the key is missing
      +
      +['a', 'b', 'a', 'a'].each do |letter|
      +    h[letter] += 1
      +end
      +
      + + +
      +
      + + +
      + + +

      Exercise summary

      + +

      In the last exercise you will have learnt a number of things about hashes. Here is a summary of the important points:

      + +

      Accessing and setting elements

      +
      h = {'one' => 1, 'two' => 2, 'three' => 3}
      +
      +h['one'] #=> 1
      +h['four'] #=> nil
      +
      +h['five'] = 5
      +h['one'] = 1.0
      +
      +h #=> {'one' => 1.0, 'two' => 2, 'three' => 3, 'five' => 5}
      +
      +
        +
      • You access an element via its key: h['one']
      • + +
      • If the key isn’t in the hash this will give nil
      • + +
      • You add new elements by setting their key
      • + +
      • If the key already exists its value will be updated
      • +
      + +

      Methods

      + +

      Hashes have a number of methods, which behave as you would expect e.g.

      + +
        +
      • length
      • + +
      • empty?
      • + +
      • keys, values
      • + +
      • has_key?, has_value?
      • +
      + +

      Iterating

      + +

      Just like an Array, you can iterate over a Hash using the each method. Unlike array iteration, in hash iteration the block accepts two parameters: the key and the value:

      +
      h = {'one' => 1, 'two' => 2, 'three' => 3}
      +
      +h.each do |key, value|
      +	puts "#{key} = #{value}"
      +end
      +
      +

      Combining hashes

      + +

      Combining hashes is done by using the merge method. The values from the second hash are added to the first, replacing them if they already exist. You will often see this used in rails for specifying default options to a function:

      +
      # note how the first version of b gets overwritten
      +{'a' => 1, 'b' => 2}.merge({'b'=>3, 'c'=>4}) #=> {'a'=>1, 'b'=>3, 'c'=>4}
      +
      +# real life example
      +def print_names(opts)
      +	default_opts = {'fancy_format' => true, 'max_length' => 20}
      +
      +	# replace the defaults with options supplied
      +	my_opts = default_opts.merge(opts) 
      +
      +	if my_opts['fancy_format']
      +		# ....
      +	end
      +
      +	#...
      +end
      +
      +

      The options example above is a common use of a hash in real life code.

      + +

      Using a hash for counting

      + +

      One special use of a hash is for counting things. The following code is an example of how to do this.

      +
      h = {}
      +
      +['a', 'b', 'a', 'a'].each do |letter|
      +    if h.has_key?(letter)
      +        # if the letter is already in the hash, increase
      +        # its count by 1
      +        h[letter] += 1
      +    else # letter isn't in the hash
      +        # so put it in and set the count to 1
      +        h[letter] = 1
      +    end
      +end
      +
      +h #=> {'a' => 3, 'b' => 1}
      +
      +

      You can make this example a bit shorter by using a hash with a default value: normally a hash will return nil if the key isn’t there, but we can set it up to return something else. In particular we’ll set it up to return 0:

      +
      # set up a hash with default value 0
      +h = Hash.new(0)
      +
      +['a', 'b', 'a', 'a'].each do |letter|
      +    h[letter] = h[letter] + 1
      +end
      +
      +h #=> {'a' => 3, 'b' => 1}
      +
      +

      If the letter isn’t in the hash yet, the default value of 0 will be returned. Otherwise the current count will be returned. Either way, we just need to increase the value by 1.

      + +
      + + +
      + + +

      Symbols

      + +

      Symbols are a bit like strings that can’t be changed. They’re primarily used to save space and time:

      + +
        +
      • Every time you write a string in ruby it has to store a new copy of it in case it is changed.
      • + +
      • Every time you compare two strings it has to check every letter to see if they’re the same.
      • + +
      • As symbols can’t be changed, it allows ruby to only store them once.
      • + +
      • This makes it quick to compare, as you can just check to see if it’s in the same storage location.
      • +
      + +

      So far we’ve used strings for our hash keys. As we write and compare hash keys a lot, it makes sense to use symbols instead.

      +
      "hello"
      +:hello
      +
      :hello.to_s
      +"hello".to_sym
      +
      +
      +"hello" << " world"
      +:hello << :" world"
      +
      +"hello".object_id
      +
      +:hello.object_id
      +
      +
      + + +
      + + +

      Sending email

      + +

      Today we’ll be looking at sending email from a ruby program. To do this we’ll be using a library called Pony. Pony is a light-weight, simple library (in comparison more fully fledged options like ActionMailer). After a small amount of configuration, it allows you to send emails with a single command.

      + +

      We’ll be using a google account to send the email - you will need to input your username and password, and it will look like the email came from your gmail account. Using gmail is a good solution for a small test app like this. When you get bigger you will start hitting gmails sending limits, and you will want to investigate other solutions e.g. sendgrid or mandrill. For further options see the heroku addons page.

      + +

      Before sending an email we need to set up some configuration. We do this by setting the Pony.options hash:

      +
      Pony.options = {
      +  :via => 'smtp',
      +  :via_options => {
      +    :address              => 'smtp.gmail.com',
      +    :port                 => '587',
      +    :enable_starttls_auto => true,
      +    :user_name            => 'yourusername',
      +    :password             => 'yourpassword',
      +    :authentication       => :plain, # :plain, :login, :cram_md5, no auth by default
      +    :domain               => "localhost.localdomain" # the HELO domain provided by the client to the server
      +  }
      +}
      +
      +

      To send the email is then very simple:

      +
      Pony.mail(:to => 'example@example.com', :subject => "Wow - an email", :body=>"Hi. This is your program speaking. Bye.")
      +
      +

      You can find out more about the different options you can use on the pony github page.

      +
      Task: +
        +
      1. +

        Fork and clone the code for this session: https://github.com/code61/sinatra_c3s4

        +
      2. + +
      3. +

        Install the gems (including pony):

        + +
         bundle install
        +
      4. + +
      5. +

        Copy and paste the contents of development_pony_options.rb.sample into a new file. Save this file as development_pony_options.rb. Fill in your gmail (or university) account details.

        +
      6. + +
      7. +

        In irb type require &#39;pony&#39;, then copy and paste in your updated options.

        +
      8. + +
      9. +

        Send an email to yourself e.g.:

        +
      10. +
      +
      Pony.mail(:to => 'example@example.com', :subject => "Wow - an email", :body=>"Hi. This is your program speaking. Bye.")
      +
      +
        +
      1. Try running the sinatra app: ruby app.rb.
      2. + +
      3. The form submission doesn't do anything at the moment. Can you work out what's wrong, and fix it?
      4. +
      +
      +
      + + +
      + + +

      Email templates

      + +

      So far the body of our email has only been a single line. What if we want a proper multi-line email? You can use erb templates for this!

      +
        Pony.mail( :to => @email,
      +             :subject => "Congratulations, you added a fruit!",
      +             :body => erb(:email, :layout => false)   )
      +
      +

      The important bit is erb(:email, :layout => false), which tells sinatra to find views/email.erb and run it through erb (to replace any <%= %> tags). The :layout => false tells sintra to skip the normal layout file: we want to send the user the raw text, not an html page! The result is then used as the email’s body.

      + +

      The template will look something like this:

      + +
      Hello there!
      +
      +<%= @name %> is a great fruit!
      +
      +Best,
      +
      +The FruitApp team
      +
      Task: +
        +
      1. Add the required line of code in the post &#39;/&#39; block, to send a welcome email to the new user.
      2. + +
      3. Modify views/email.erb so that it (at least) contains the name of the person who just signed up.
      4. + +
      5. (Optional extension) deploy your app to heroku. You will need to add the (free version) of the sendgrid addon to allow you to send emails.
      6. + +
      7. (Alternative extension) Clone down the project https://github.com/code61/mailmerge and have a play!
      8. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish off any exercises from class.
      2. + +
      3. Do the Codecademy Ruby track Sections 7 and 8.
      4. +
      +
      +
      + + +
      + + +

      (Ext) Arrays and back

      + +

      This page is more advanced. This stuff is sometimes useful, but don’t worry if you want to skip over it the first time through.

      + +

      Converting to arrays and back

      + +

      You can convert a hash to an array using the to_a method and use the Hash[ ] syntax to convert it back:

      +
      h = {'a' => 1, 'b' => 2}
      +
      +h.to_a #=> [['a', 1], ['b', 2]]
      +
      +h2 = Hash[['a', 1], ['b', 2]]
      +
      +

      The Hash[ ] is also useful for creating a hash from arrays of keys and values (which is surprisingly useful).

      +
      keys = [1, 2, 3]
      +values = ['one', 'two', 'three']
      +
      +# use Array#zip to get the arrays in the right format
      +zipped = keys.zip(values)  #=> [[1, 'one'], [2, 'two'], [3, 'three']]
      +
      +h = Hash[zipped]  #=> {1 => 'one', 2 => 'two', 3 => 'three'}
      +
      Task: +

      (Optional)

      + +
        +
      1. Work through the following examples, copying and pasting into irb.
      2. + +
      3. See if you can do the challenge at the end.
      4. +
      +
      # A few new ways to create a hash
      +# -------------------------------
      +
      +h1 = Hash['a', 1, 'b', 2, 'c', 3]
      +
      +h2 = Hash[[['a',1],['b',2],['c',3]]]
      +
      +
      +# Converting to arrays (and back?)
      +# -------------------------------
      +
      +h = {'a'=>1, 'b'=>2, 'c'=>3}
      +
      +a = h.to_a
      +
      +# How could you convert a back into h?
      +
      +h = {'one'=>1, 'two'=>2, 'three'=>3}
      +
      +keys = h.keys
      +values = h.values
      +
      +# How would you combine keys and values back into h?
      +
      + +
      +
      + + +
      + + +

      (Ext) Exercise summary

      + +

      It’s easy to convert a hash into an array.

      +
      h = {'a'=>1, 'b'=>2, 'c'=>3}
      +
      +a = h.to_a
      +# => [["a", 1], ["b", 2], ["c", 3]] 
      +
      +

      To convert back from an array to a hash, use

      +
      h=Hash[a]
      +# => {"a"=>1, "b"=>2, "c"=>3} 
      +
      +

      You can unpack a hash into its keys and values with the .keys and .values methods

      +
      h = {'one'=>1, 'two'=>2, 'three'=>3}
      +
      +keys = h.keys
      +#=> ["one", "two", "three"] 
      +values = h.values
      +#=> [1, 2, 3] 
      +
      +

      and put it back together with

      +
      h = Hash[keys.zip(values)]
      +
      +# => {"one"=>1, "two"=>2, "three"=>3} 
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c4s1/index.html b/c4s1/index.html new file mode 100644 index 0000000..3c2d019 --- /dev/null +++ b/c4s1/index.html @@ -0,0 +1,291 @@ + + + + + + Further Web Programming with Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Improving code

      + +

      This session we’re going to be looking at ways to improve the code you write. In particular, we’re going to see how to use functions to begin to separate out program logic into reusable chunks.

      + +

      Why do we need functions?

      + +

      Take a look at this bit of code taken from a sinatra app:

      +
      @swimmer_first_name   = @swimmer[:name].split.first
      +@swimmer_last_name    = @swimmer[:name].split.last
      +@swimmer_dob          = @swimmer[:dob]
      +
      +@cyclist_first_name   = @cyclist[:name].split.first
      +@cyclist_last_name    = @cyclist[:name].split.last
      +@cyclist_dob          = @cyclist[:dob]
      +
      +@runner_first_name    = @runner[:name].split.first
      +@runner_last_name     = @runner[:name].split.last
      +@runner_dob           = @runner[:dob]
      +
      +

      This code contains a lot of repetition. Some of the repetition might be unavoidable: we might really need to set up all those different instance variables to share with a view. Other bits aren’t and will cause us problems in the long run.

      + +

      The duplication of the logic for extracting the first and last name is particularly problematic:

      + +
        +
      • If we wanted to change the way a last name was extracted from a name (e.g to take into account names like ‘Pierre de Fermat’) we’d have to make changes in three places.
      • + +
      • The code is also cluttered and harder to make sense of than it needs to be: each time you read .split.first your brain has to convert that into ‘find the first name’. As a programmer you will spend more time reading code than writing it, so these considerations are important.
      • +
      + +

      A nicer way to write this code would be to use first_name and last_name functions, that contain the logic for splitting up the name:

      +
      @swimmer_first_name   = first_name(@swimmer[:name])
      +@swimmer_last_name    = last_name(@swimmer[:name])
      +@swimmer_dob          = @swimmer[:dob]
      +
      +@cyclist_first_name   = first_name(@cyclist[:name])
      +@cyclist_last_name    = last_name(@cyclist[:name])
      +@cyclist_dob          = @cyclist[:dob]
      +
      +@runner_first_name    = first_name(@runner[:name])
      +@runner_last_name     = last_name(@runner[:name])
      +@runner_dob           = @runner[:dob]
      +
      Task: +
        +
      1. Clone down the sinatra app for this session: https://github.com/code61/sinatra_c4s1.
      2. + +
      3. Install the required libraries: cd sinatra_c4s1 and then bundle install.
      4. + +
      5. Familiarise yourself with the app, by looking through the code and running the app from the command line (ruby app.rb).
      6. + +
      7. See if you can identify other places where the logic could be cleaned up.
      8. +
      +
      +
      + + +
      + + +

      Functions

      + +

      A function (or method) is a way of separating out a piece of programming logic so that you can use it elsewhere.

      + +

      Defining and calling a function

      + +

      There are two steps in using a function

      + +
        +
      1. Define the function: to define a function you need to give it a name and write the code contained in the function.
      2. + +
      3. Call the function: when you use the function, we say that the function is being ‘called’. Calling a function causes the code inside it to be run.
      4. +
      +
      def first_name(full_name)
      +  full_name.split.first
      +end
      +
      +first_name('Tom Close') #=> 'Tom'
      +first_name('Ashok Menon') #=> 'Ashok'
      +
      +

      In the example above the function takes a single parameter (in this case the full name that you want to split up).

      + +
        +
      • When you call the function you give it the full name (e.g. "Tom Close") as a string.
      • + +
      • The the variable full_name, that you specified in the function definition, is set to the name you provided. In this case this is equivalent to full_name = "Tom Close".
      • + +
      • The statements inside the function body are then executed.
      • + +
      • The function returns the value of the last expression to be evaluated.
      • +
      +
      Task: +
        +
      1. Fork and clone down the exercises for this session: https://github.com/code61/exercises_c4s1
      2. + +
      3. Install the gems you need - in the exercises_c4s1 folder, run: bundle install
      4. + +
      5. Open names.rb in sublime text.
      6. + +
      7. Using the code above fill out the first_name function.
      8. + +
      9. Open irb and load in the file by running load &#39;names.rb&#39;.
      10. + +
      11. Try the function out, by calling it in irb.
      12. + +
      13. Close irb and run the tests we've provided for the function by running rspec spec/first_name_spec.rb.
      14. + +
      15. Now try and write the body of the last_name function. Follow the same procedure of trying in irb, then running the test rspec spec/last_name_spec.rb.
      16. + +
      17. (Ext) Improve your last_name function, so that it can cope with composite last names (treating everything after the first name as the last name). Test your solution by running rspec spec/ext_last_name_spec.rb
      18. + +
      19. (Ext) Work through the functions in dates.rb. Test your solutions running the tests in files spec/month_spec.rb, spec/last_digit_spec.rb, spec/penultimate_digit_spec.rb, spec/ordinal_suffix_spec.rb and spec/date_in_words_spec.rb.
      20. +
      +
      +
      + + +
      + + +

      More about arguments

      + +

      So far we’ve only looked at functions with a single argument. What if we want to have no parameters, multiple parameters or a variable number?

      + +

      Functions with no parameters

      + +

      It is sometimes useful to have a function with no parameters, often for a task that you need to perform repetitively:

      +
      require 'csv'
      +
      +def load_data
      +  # read data in from the csv file
      +  data = CSV.read('tmp/students/data.csv')
      +
      +  # remove the header row
      +  data[1..-1]
      +end
      +
      +

      When you call a function with no parameters, you don’t need to use brackets:

      +
      load_data #=> [[..], [..], [..], ...]
      +

      [In fact you don't need brackets when you're calling a function with arguments either. For the time being we'll use them though, to keep things simple.]

      +

      Functions with multiple parameters

      + +

      Defining and calling a function with multiple parameters is just like defining and calling one with a single parameter:

      +
      def insult(word, strength)
      +  "#{word.capitalize} off" + '!' * strength
      +end
      +
      +insult('goose', 4) #=> "Goose off!!!!"
      +
      +

      When you call a function with multiple parameters, you need to make sure you provide the right number, otherwise you’ll get an error.

      +
      insult('badger', 4, 5)
      +#=> ArgumentError: wrong number of arguments (3 for 2)
      +#=> from (pry):2:in `insult'
      +
      +

      Functions with optional parameters

      + +

      Sometimes it’s useful to be able to supply a parameter if you want, but use a sensible default otherwise:

      +
      def i_love(thing = 'ruby')
      +  "I love #{thing}!"
      +end
      +
      +i_love('coding') #=> "I love coding!"
      +i_love           #=> "I love ruby!"
      +
      Task: +
        +
      1. Open more_functions.rb and begin to work your way throught the functions in the file.
      2. + +
      3. For each function you write, reload the file into irb to try it out: load &#39;more_functions.rb&#39; (run this inside irb).
      4. + +
      5. For each function you write, run the appropriate test e.g.: rspec spec/multiply_and_sum_spec.rb (run this outside irb, on the command line).
      6. + +
      7. If you get onto the describe_result function, you will need to start by writing your own test in spec/describe_result_spec.rb. (Do this by copying and pasting from another test, and make the appropriate changes.)
      8. +
      +
      +
      + + +
      + + +

      Refactoring

      + +

      Refactoring is the act of restructuring a piece of code without changing its behaviour. Refactoring is very important in software development, as without it software projects quickly become unweildy and difficulat to work with.

      + +

      You’re going to refactor the sinatra app, by completing the functions in the helper_functions.rb file.

      +
      Task: +
        +
      1. Open app.rb in Sublime Text.
      2. + +
      3. Uncomment the commented out post block at the bottom, and comment out the other one. This is how we want the code to look, but currently the functions aren't there to make this work.
      4. + +
      5. Uncomment the line require &#39;./helper_functions&#39; at the top of app.rb
      6. + +
      7. Open the file helper_functions.rb in Sublime Text. Complete the functions so that the app works as before.
      8. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish off any exercises from class.
      2. + +
      3. Do the Codecademy Ruby track Sections 9 and 10.
      4. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c4s2/index.html b/c4s2/index.html new file mode 100644 index 0000000..8799ea8 --- /dev/null +++ b/c4s2/index.html @@ -0,0 +1,467 @@ + + + + + + Further Web Programming with Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Revisiting functions

      + +

      Last time we looked at splitting small bits of program logic out into functions.

      +
      # Extracts the first name from a full name.
      +#
      +#   first_name('Tom Close') #=> 'Tom'
      +#   first_name('Alan Jones') #=> 'Alan'
      +#
      +def first_name(full_name)
      +  full_name.split.first
      +end
      +
      +

      This then allowed us to reuse this logic in different places:

      +
      post '/' do
      +  @event   = params[:event]
      +  @swimmer = params[:swimmer]
      +  @cyclist = params[:cyclist]
      +  @runner  = params[:runner]
      +
      +  @event_name = event_name(@event)
      +  @event_date = event_date(@event)
      +
      +  @swimmer_first_name   = first_name(@swimmer[:name])
      +  @swimmer_last_name    = last_name(@swimmer[:name])
      +  @swimmer_dob          = @swimmer[:dob]
      +
      +  @cyclist_first_name   = first_name(@cyclist[:name])
      +  @cyclist_last_name    = last_name(@cyclist[:name])
      +  @cyclist_dob          = @cyclist[:dob]
      +
      +  @runner_first_name    = first_name(@runner[:name])
      +  @runner_last_name     = last_name(@runner[:name])
      +  @runner_dob           = @runner[:dob]
      +
      +  erb :tickets
      +end
      +
      +

      This form still isn’t ideal though:

      + +
        +
      • we have 3 competitors, but are passing around 9 different variables. If the tickets template were to become more complicated, things will only get worse.
      • + +
      • we have the first_name logic separated out, but the functions are separate from the data that they act on. We have to keep track of both these things throughout the program.
      • +
      + +

      Today we’re going to be looking at a solution to this problem: we’re going to be looking at classes, which will let us package up data with the functions that act on them.

      + +

      This will allow us to change the code so that it looks more like this:

      +
      post '/' do
      +  @event   = Event.new(params[:event])
      +  @swimmer = Person.new(params[:swimmer])
      +  @cyclist = Person.new(params[:cyclist])
      +  @runner  = Person.new(params[:runner])
      +
      +  erb :tickets
      +end
      +
      +

      we’ll then use this in the templates as follows:

      +
      <table class="table">
      +  <tr>
      +    <th>First Name</th>
      +    <th>Last Name</th>
      +    <th>D.O.B</th>
      +  </tr>
      +  <tr>
      +    <td><%= @cyclist.first_name %></td>
      +    <td><%= @cyclist.last_name %></td>
      +    <td><%= @cyclist.dob %></td>
      +  </tr>
      +</table>
      +
      +

      Instead of passing the @cyclist data to various functions, we’re calling methods on a new Person object, that we’ve created.

      +
      Task: +
        +
      1. Clone down the sinatra app for the session: https://github.com/code61/sinatra_c4s2
      2. + +
      3. Install the gems for the app: bundle install.
      4. + +
      5. Have a quick look at the commented out section at the bottom of app.rb to get an idea of where we're going.
      6. +
      +
      +
      + + +
      + + +

      Introducing classes

      + +

      A class

      + +
        +
      • you can view a class as a blueprint for a set of behaviour
      • + +
      • an instance of a class is called an object
      • +
      + +

      Classes are common to many programming languages. Languages that use classes to organise their logic are often referred to as Object-Oriented programming languages. Apart from ruby, other object-oriented programming languages include python, c++ and Java, meaning that the vast majority of code written at the moment is object-oriented code.

      + +

      Ruby is a more object-oriented language than most: in ruby every value (e.g. integers, strings, arrays, hashes, etc.) is an object.

      + +

      Have a look at the following use of a Circle object:

      +
      c = Circle.new(10)
      +
      +c.radius #=> 10
      +c.area   #=> 314.2
      +
      +

      The circle object holds the data, or attributes, of the circle (in this case just the radius) and has methods to perform operations (in this case calculating the area), using that data.

      + +

      We define the behaviour of this object using a class. You can view a class as a blueprint for a given type of object. We say that the objects that follow the blueprint that the class defines are instances of the class.

      +
      class Circle
      +  def initialize(radius)
      +    @radius = radius
      +  end
      +
      +  def radius
      +    @radius
      +  end
      +
      +  def area
      +    3.142 * @radius * @radius
      +  end
      +end
      +
      +

      There are a few things to note here:

      + +
        +
      • The initialize method is run when you create the instance of the class e.g. c = Circle.new(10)
      • + +
      • Instance variables (beginning with @) are used to hold the attributes of the object e.g. @radius. Instance variables can be used inside any of the class’s methods.
      • +
      +
      Task: +
        +
      1. Clone down the code for the session: https://github.com/code61/exercises_c4s2.git
      2. + +
      3. Run bundle install to grab the required gems.
      4. + +
      5. Have a look at circle.rb in sublime text: +
          +
        • load it into irb: load &#39;./circle.rb&#39;
        • + +
        • create a circle: c = Circle.new(5)
        • + +
        • check its radius and area: c.radius and c.area
        • + +
        • write the contents of the missing circumference method
        • + +
        • run the tests: rspec spec/circle_spec.rb (on the command line not irb)
        • +
        +
      6. + +
      7. Open square.rb in sublime text: +
          +
        • write the missing methods
        • + +
        • load it into irb to check they work
        • + +
        • run the tests: rspec spec/square_spec.rb (on the command line)
        • +
        +
      8. + +
      9. Open person.rb in sublime text: +
          +
        • write the missing methods
        • + +
        • load it into irb to check they work
        • + +
        • run the tests: rspec spec/person_spec.rb (on the command line)
        • +
        +
      10. + +
      11. (Ext) have a look in mastermind.rb and guess.rb. +
          +
        • Write the missing methods in guess.rb.
        • + +
        • Run the tests to check it works.
        • + +
        • Use the Guess class you've just written to help write the missing methods in mastermind.rb
        • + +
        • Run the mastermind tests to check it works.
        • +
        +
      12. +
      +
      +
      + + +
      + + +

      Changing attributes

      + +

      So far we’ve just seen attributes that have been set when the class is instantiated. It’s also possible to update attributes throughout the lifecycle of the object. Have a look at the following code:

      +
      class Child
      +  def initialize(age)
      +    @age = age
      +  end
      +
      +  def age
      +    @age
      +  end
      +
      +  def age=(new_age)
      +    @age = new_age
      +  end
      +
      +  def have_birthday
      +    @age = @age + 1
      +    "You are now #{@age} years old!"
      +  end
      +end
      +
      +

      It can be used as follows:

      +
      c = Child.new(5)
      +c.age #=> 5
      +
      +c.age = 6
      +c.age #=> 6
      +
      +c.have_birthday #=> "You are now 7 years old!"
      +c.age #=> 7
      +
      Task: + +

      Update your solution in person.rb to allow the first_name and last_name to be set independently, and have the name update accordingly:

      + + +
      p = Person.new({:name => "Bart Simpson", :dob => "15/1/1990"})
      +
      +p.name #=> "Bart Simpson"
      +
      +p.first_name = "Bartholomew"
      +p.name #=> "Bartholomew Simpson"
      +
      +

      You might need to make changes to which attributes your class stores, to make this work.

      + +

      Test your work by running rspec spec/person_update_spec.rb.

      +
      +
      + + +
      + + +

      Putting it all together

      + +

      We’re now going to return to the sinatra app and use classes to refactor the app again.

      +
      Task: +
        +
      1. Gather up all the data and methods to do with people into a Person class: +
          +
        • Copy your Person class from the exercise into sinatra_c4s2/person.rb.
        • + +
        • Uncomment the require &#39;./person&#39; at the top of app.rb.
        • + +
        • Rewrite the person code in the post block to use your class.
        • + +
        • Change views/tickets.erb to call method on the objects you pass through.
        • + +
        • Check the app still works as before!
        • +
        +
      2. + +
      3. Gather up all the event-related code into a new Event class: +
          +
        • Write the necessary code in event.rb.
        • + +
        • Uncomment the require &#39;./event&#39; at the top of app.rb.
        • + +
        • Rewrite the event code in the post block.
        • + +
        • Change the views to use the objects.
        • + +
        • Check the app works as before.
        • +
        +
      4. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish off any exercises from class.
      2. + +
      3. Do the Codecademy Ruby track Sections 16 and 17. (If you have time, do the inbetween ones too!)
      4. +
      +
      +

      Further reading

      + +

      We have only really begun to touch on what you can do with classes in ruby. There are really important concepts in object oriented programming (e.g. inheritance, class methods, class variables, mixins, etc.) that we haven’t really mentioned at all. We’ll meet some of these things in the next few weeks, but if you want a more comprehensive overview you can take a look at one of the following:

      + + + +

      Getting set up with MongoDB

      + +

      Next session we will look at storing information in a database. The database we’ll be using is MongoDB.

      + +

      To use mongodb you need to have it running on your laptop. The database will run on one of your localhost ports (like sinatra), so that other processes can connect to it.

      + +

      The preparation falls into four parts:

      + +
        +
      1. Install MongoDB.
      2. + +
      3. Start running the database.
      4. + +
      5. Install the gems to allow ruby to connect to MongoDB.
      6. + +
      7. Test your installation.
      8. +
      + +

      We will look at these parts separately.

      + +

      Install MongoDB

      + +

      If you installed homebrew (“The Hard Way”, Mac only), your task is now easy. At the command line write:

      + +
      brew install mongo
      + +

      If you didn’t install homebrew (i.e. try doing the above and it doens’t work), you will need to download MongoDB from the site and follow the installation instructions for your system.

      +
      Task: +

      Install MongoDB either via

      + +
      $ brew install mongo
      + +

      or by downloading and installing from the MongoDB website.

      +
      +

      Start MongoDB running

      + +

      You can start MongoDB running from the command line:

      + +
      $ mongod
      + +

      You will need to keep this command line open and open a new one to continue the instructions.

      + +

      By default mongo will run on localhost:28017. If you visit that link in your browser you should see a mongo stats page.

      +
      Task: +
        +
      1. +

        Start MongoDB:

        + +
         $ mongod
        +
      2. + +
      3. +

        Check the service is running at localhost:28017.

        +
      4. +
      +
      +

      Install the gems and test

      + +

      I’ve set up a project with the gems you need, so this should be straightforward:

      +
      Task: +
        +
      1. +

        Clone the project:

        + +
         $ git clone https://github.com/code61/mongo_test.git
        +
      2. + +
      3. +

        Move into that folder and install the gems:

        + +
         $ cd mongo_test
        + $ bundle install
        +
      4. + +
      5. +

        Test your installation:

        + +
         $ ruby main.rb
        + +

        If you see the text "Everything worked ok!", you're good to go!

        +
      6. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c4s3/index.html b/c4s3/index.html new file mode 100644 index 0000000..de893c3 --- /dev/null +++ b/c4s3/index.html @@ -0,0 +1,464 @@ + + + + + + Further Web Programming with Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      About MongoDB

      + +

      In this session we will be using a database - a specialised piece of software for storing and retrieving data. Databases become important when you have large amounts of data, which you want to be able to access quickly and which you want to keep consistent.

      + +

      In the session we will be using two different, but related, pieces of software:

      + +
        +
      • MongoDB the database.
      • + +
      • Mongoid a ruby library that we will use to interface with MongoDB.
      • +
      + +

      MongoDB is one of many different databases that we could have chosen. We went with MongoDB because it is fairly straight-forward to configure and quick to get going with. It is also fairly popular in the web community at the moment.

      + +

      MongoDB is a NOSQL, or document-based, database. In the past, the more traditional style SQL, or relational, databases were used in most applications. NOSQL databases have risen in popularity in the last year or two, in part due to their ability to offer increased performance in certain common scenarios, by allowing developers to bend the rigid SQL database structures. We will go into this in slightly more depth later in the course. For the time being, with data we’re storing in the next few sessions it won’t make much difference whether our db is SQL or NOSQL.

      + +

      Using Mongoid

      + +

      Mongoid is a ruby library that allows you to interface with MongoDB. The idea is very simple - you can think of Mongoid as mapping classes in your application to tables in the database. Take a look at the following example:

      +
      class Athlete
      +  include Mongoid::Document
      +
      +  field :name,    type: String
      +  field :country, type: String
      +  field :age,     type: Integer
      +  field :height,  type: Integer
      +  field :weight,  type: Integer
      +  field :sex,     type: String
      +  field :dob,     type: Time
      +  field :gold,    type: Integer
      +  field :silver,  type: Integer
      +  field :bronze,  type: Integer
      +  field :sport,   type: Integer
      +  field :events,  type: Array
      +
      +  def total_medals
      +    gold + silver + bronze
      +  end
      +end
      +
      +

      This is fairly similar to the classes we looked at last week - we have data and methods that act on the data. The two different parts are:

      + +
        +
      • include Mongoid::Document: this activates this class as a mongoid-enabled class.
      • + +
      • The field :name, type: String etc.: these setup the getting and setting methods that we had to do by hand last week, and tell mongoid what sort of object it is, which is useful for storage purposes.
      • +
      + +

      You can use this class like this:

      +
      a = Athlete.new
      +a.name    = "Michael Phelps"
      +a.country = "US"
      +a.sport   = "Swimming"
      +a.gold    = 2
      +a.silver  = 2
      +a.bronze  = 0
      +
      +a.name         #=> "Michael Phelps"
      +a.total_medals #=> 4
      +
      +

      This is not that exciting - we could have done all this last week. It gets more interesting when we start using some of the extra methods that Mongoid has added to the Athlete class:

      +
      # Let's save Michael in the database
      +a.save    #=> true
      +
      +# How many athletes do we have?
      +Athlete.count  #=> 1
      +
      +# Let's pull Michael out again
      +a = Athlete.first #=> #<Athlete _id: 5315dec6de9c928a02001c9c, name: "Michael Phelps", country: "US", gold: 2, silver: 2, bronze: 0, sport: "Swimming">
      +
      +# or
      +a = Athlete.find_by(:name => "Michael Phelps") #=> #<Athlete _id: 5315dec6de9c928a02001c9c, name: "Michael Phelps", country: "US", gold: 2, silver: 2, bronze: 0, sport: "Swimming">
      +
      +

      Starting MongoDB

      + +

      In order to use MongoDB in a ruby project, it first needs to be running on your computer. The command for this is

      + +
      $ mongod
      + +

      You will need to keep this command line open and continue the instructions in a new one.

      + +

      By default mongo will run on localhost:28017. If you visit that link in your browser you should see a mongo stats page.

      +
      Task: +
        +
      1. Start MongoDB running on your laptop.
      2. + +
      3. Clone down the code for the session: https://github.com/code61/sinatra_c4s3
      4. + +
      5. Run bundle install to get the required gems.
      6. + +
      7. Open up irb.
      8. + +
      9. Type require &#39;./utils&#39; (this loads in the Athlete class and sets up your MongoDB connection).
      10. + +
      11. Try the following
      12. +
      +
      a = Athlete.new
      +a.name    = "Michael Phelps"
      +a.country = "US"
      +a.sport   = "Swimming"
      +a.gold    = 2
      +a.silver  = 2
      +a.bronze  = 0
      +
      +a.name
      +a.country
      +
      +a.save
      +
      +Athlete.count
      +b = Athlete.first
      +
      +b.name
      +b.name = "Tom Close"
      +
      +a.name     # has this updated?
      +
      +b.save
      +a.name     # has it updated now?
      +
      +a.reload
      +a.name
      +
      +# different way of creating an athlete, using a hash
      +c = Athlete.new(:name   => "Chad Le Clos", :country => "South Africa", 
      +                :sport  => "Swimming",     :gold    => 1,
      +                :silver => 1,              :bronze  => 0 )
      +c.save
      +
      +d = Athlete.find_by(:name => "Chad Le Clos")
      +
      + +
      +
      + + +
      + + +

      Searching and sorting

      + +

      One thing that databases are good at is searching for records. Mongoid allows you to search for records in various different ways:

      +
      Athlete.find_by(:name => "Michael Phelps")
      +
      +Athlete.find_by(:gold => 2)   # returns the first one it finds
      +
      +Athlete.where(:gold => 2)     # returns a 'collection' with all of them
      +
      +# you can do lots of things with collections e.g. counting
      +Athlete.where(:gold => 2).count
      +# or iterating
      +Athlete.where(:gold => 2).each do |a|
      +  puts a.name
      +end
      +# or summing
      +Athlete.where(:gold => 2).sum(:age)
      +# or turn it into an array
      +Athlete.where(:gold => 2).to_a
      +
      +# searching on multiple things at once
      +Athlete.where(:gold => 2, :bronze => 3)
      +# or
      +Athlete.where(:gold => 2).where(:bronze => 0)
      +
      +# searching on conditions
      +Athlete.where(:gold.gte => 2)
      +
      +

      You can find further examples in the Mongoid docs.

      + +

      Sorting

      + +

      You can also get the database to return things to you sorted:

      +
      # these both return collections
      +Athlete.order_by(:age.asc)
      +Athlete.order_by(:age.desc)
      +
      +# you can then do things like
      +# .. take the first 1
      +Athlete.order_by(:age.asc).first
      +
      +# .. or the first 10
      +Athlete.order_by(:age.asc).limit(10).to_a
      +
      Task: +
        +
      1. Open irb and do require &#39;./utils&#39;.
      2. + +
      3. Call the function load_athletes. This loads in all the athletes from London 2012.
      4. + +
      5. Answer the following questions: +
          +
        1. How many athletes were there?
        2. + +
        3. How many women? How many men?
        4. + +
        5. Who was the oldest athlete?
        6. + +
        7. Who was the youngest?
        8. + +
        9. How many people won at least 1 gold?
        10. + +
        11. What was the average age? (Your answer should have decimal places..)
        12. + +
        13. Who got the most golds?
        14. + +
        15. Who was the 10th oldest athlete?
        16. +
        +
      6. +
      +
      +
      + + +
      + + +

      Exercise answers

      + +
      1. How many athletes were there?
      +2. How many women? How many men?
      +3. Who was the oldest athlete?
      +4. Who was the youngest?
      +4. How many people won at least 1 gold?
      +5. What was the average age? (Your answer should have decimal places..)
      +6. Who got the most golds?
      +7. Who was the 10th oldest athlete?
      +
      Athlete.count
      +#=> 10384 
      +
      +Athlete.where(:sex=>"M").count
      +#=> 5756 
      +
      +Athlete.where(:sex=>"F").count
      +#=> 4628 
      +
      +Athlete.order_by(:age.desc).first.name
      +#=> "Hiroshi Hoketsu" 
      +
      +Athlete.order_by(:age.desc).last.name
      +#=> "Adzo Kpossi" 
      +
      +Athlete.where(:gold.gt => 0).count
      +#=> 162 
      + 
      +Athlete.sum(:age)/Athlete.count.to_f
      +#=> 26.06885593220339
      +
      +Athlete.order_by(:gold.desc).limit(11).each do |a|
      +   puts a.name
      +   puts a.gold
      +end
      +#=>Yannick Agnel
      +#=>2
      +#=>Bo Bae Ki
      +#=>2
      +#=>Elisa Di Francisca
      +#=>2
      +#=>Gabrielle Douglas
      +#=>2
      +#=>Missy Franklin
      +#=>2
      +#=>Michael Jung
      +#=>2
      +#=>Ryan Lochte
      +#=>2
      +#=>Michael Phelps
      +#=>2
      +#=>Allison Schmitt
      +#=>2
      +#=>Dana Vollmer
      +#=>2
      +#=>Shiwen Ye
      +#=>2
      +
      + Athlete.order_by(:age.desc)[9].name
      + => "Irada Ashumova" 
      +
      +
      + + +
      + + +

      Mongo with sinatra

      + +

      Setting up Sinatra to work with Mongoid

      + +

      To get sinatra to work with Mongoid you will need to do the following things:

      + +
        +
      1. Add gem 'mongoid' to your Gemfile (and bundle install).
      2. + +
      3. Create a mongoid.yml file with your Mongoid settings (see below).
      4. + +
      5. Load mongoid and connect to the database
      6. +
      + +

      For local development, you will also need to make sure MongoDB is running on your laptop - type mongod at the command line.

      + +
      Mongoid.yml
      + +

      The mongoid.yml file specifies the options you need to connect to a MongoDB database. The following should work:

      +
      development:
      +  sessions:
      +    default:
      +      hosts:
      +        - localhost:27017
      +      database: london2012
      +  options:
      +    raise_not_found_error: false
      +
      +production:
      +  sessions:
      +    default:
      +      uri: <%= ENV['MONGOHQ_URL'] %>
      +  options:
      +    raise_not_found_error: false
      +
      +

      There are two sections, describing different databases to connect to in development and production. You should change the development database name from ‘london2012’ to something suitable for your project. If you fail to do this, your code will still run, but eventually you’ll run into problems as data from one project turns up in another.

      + +

      The production section is set up to use MongoHQ on Heroku (see below). Sinatra can find out which environment it is running in by checking the settings.environment variable, which will return :production on Heroku and :development on your local machine. Mongoid uses this to know which part of the mongoid.yml file to look at.

      + +
      Loading libraries and connecting
      + +

      You also need to load the relevant libraries in app.rb and setup a database connection. The following code does this:

      +
      # in app.rb
      +require 'sinatra'
      +require 'mongoid'
      +require 'json'
      +
      +# Setup database connection
      +Mongoid.load!("mongoid.yml")
      +
      +get '/' do
      +# etc. etc.
      +
      +

      As well as the ‘mongoid’ and ‘sinatra’ libraries, you also need to include ‘json’, which mongoid uses to store objects in the database.

      + +

      The Mongoid.load! line is the one which uses the sinatra environment to decide which part of mongoid.yml to look at.

      + +

      Mongoid on Heroku

      + +

      If you use the mongoid.yml from above, you’ll be pretty much ready to go on Heroku. The only thing you’ll need to do is to add the MongoHQ Add-on. You can do this by logging into Heroku.

      +
      Task: +
        +
      1. Run app.rb and take a look at the site in your browser.
      2. + +
      3. Modify the application so that the 'oldest' link displays the 20 oldest athletes.
      4. + +
      5. Make changes so that the 'youngest' link displays the 20 youngest athletes.
      6. + +
      7. Add at least 2 more stats pages of your choosing.
      8. + +
      9. (Optional) Return to sinatra_c3s4. Set your app up with mongoid, so that when people sign up it stores their names and emails. You will need to: +
          +
        • Follow the steps above to add mongoid to the sinatra app.
        • + +
        • Create a mongoid-enabled User class, to store the data.
        • + +
        • Add a /list route for admins to see the list of people who've signed up.
        • + +
        • Push it to heroku.
        • + +
        • You can see a working app here. If you get stuck, you can find the code here.
        • +
        +
      10. +
      +
      +
      + + +
      + + +

      Homework

      +
      Task: +
        +
      1. Finish off any exercises from class.
      2. + +
      3. Finish off anything you haven't done from the Codecademy Ruby track!
      4. +
      +
      +
      + +
      + +
      + + + + +
      + + + + diff --git a/c4s4/index.html b/c4s4/index.html new file mode 100644 index 0000000..8fdb1fb --- /dev/null +++ b/c4s4/index.html @@ -0,0 +1,431 @@ + + + + + + Further Web Programming with Ruby + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Intro to Rails

      + +

      Rails is a web framework written in ruby. It is similar to Sinatra, except it does a lot more for you. Rails is great as it makes it possible to build serious web applications while you continue to learn about web development.

      + +

      A lot of your time as a new rails programmer will be spent figuring out how all the pieces fit together. It can seem daunting at first, however there are a huge number of excellent blog posts/tutorials/videos out there which will make your task much easier. In this session we will go through the steps involved setting up a new rails application and spend a bit of time looking around the application that is created.

      + +

      In this session we will be creating a Rails 4.0 application. Rails 4.0 is the latest version of rails and was released a few months ago. When looking at advice on the internet it’s important to be aware that some things have changed since Rails 3, and so some things may no longer apply.

      + +

      One of the nice things about rails is it does a lot of work for you. We’ll start by creating a new rails project using the rails new command:

      + +
      $ rails new project_manager
      + +

      This command has created a new folder called project_manager and filled it with the files for a basic rails application. As part of this it will have created a Gemfile to manage the dependencies and as the last step will run bundle install to download them all.

      + +

      Let’s have a quick look in this new folder:

      + +
      $ cd project_manager
      +$ ls -a
      +.gitignore
      +Gemfile
      +Gemfile.lock
      +README.rdoc
      +Rakefile
      +app
      +bin
      +config
      +config.ru
      +db
      +lib
      +log
      +public
      +test
      +tmp
      +vendor
      + +

      You’ll notice a couple of files that you recognise from sinatra: Gemfile, Gemfile.lock and config.ru. Rails has also created a .gitignore file for you so that files that shouldn’t be placed in version control aren’t.

      + +

      Rails has also created a load of folders for you, mostly with other files and folders inside. We won’t worry about all of these at the moment, but will come back to them later on.

      + +

      We can run this skeleton application by starting the rails server (similar to ruby app.rb in Sinatra). To do this type

      + +
      $ rails server
      + +

      This will probably start rails running at localhost:3000. When you visit that link you’ll find a default rails page telling you some information about your new application.

      + +

       Generating a model

      + +

      Models are the ‘the things our system is about’. For our project manager application, one of the models we will be working with will be the task model. A user will create tasks, others will be able to see the tasks and then mark them as created when they’re done. We will create the files for the task by generating a scaffold:

      + +
      $ rails generate scaffold task name:string due_date:date description:text project:string completed:boolean
      + +

      The rails generate scaffold command tells rails to set up everything to do with the task model that we’re creating (more on this later). The name of the thing that you’re creating (task in this case) should always be singular. The final part of the command name:string due_date:date description:text tells rails what attributes the model should have and what type they are. The possibilities for the types are:

      + +
      :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean
      + +

      an up-to-date list of which can be found in the rails docs.

      + +

      Among other things the generate scaffold command will have set up a database migration to set up the database table for tasks. As a final step we need to create that tale in the database:

      + +
      $ rake db:migrate
      + +

      Once you have restarted the server you should now be able to visit localhost:3000/tasks in the browser and create a task.

      +
      Task: +
        +
      1. +

        Before you start check that you're running rails 4.0:

        + +
         $ rails -v
        + Rails 4.0.0
        +
      2. + +
      3. +

        In your coding_course folder set up a new rails application:

        + +
         $ rails new project_manager
        +
      4. + +
      5. +

        Move into the project_manager folder and set it up as a git repository:

        + +
         $ cd project_manager
        + $ git init
        + $ git add --all
        + $ git commit -m &#39;Initial import&#39;
        +
      6. + +
      7. +

        Generate scaffolding for a task model:

        + +
         $ rails generate scaffold task name:string due_date:date description:text project:string completed:boolean
        +
      8. + +
      9. +

        Migrate the database:

        + +
         $ rake db:migrate
        +
      10. + +
      11. +

        Restart the server and check you can add tasks at localhost:3000/tasks.

        +
      12. + +
      13. +

        Add everything to git:

        + +
         $ git add --all
        + $ git commit -m &#39;Created tasks&#39;
        +
      14. + +
      15. +

        Have a look in app/controllers and app/views/tasks and see if you can figure out what is going on.

        +
      16. +
      +
      +
      + + +
      + + +

      Model/View/Controller

      + +

      Model/View/Controller (MVC) is an application architecture that rails is based on. It works as follows:

      + +
        +
      • The Controller deals with incoming web requests. It manages the interaction between the Models and renders the Views.
      • + +
      • The Models correspond to ‘business objects’. The Model layer is responsible for storing/retrieving the information in the database (among other things).
      • + +
      • The Views correspond to pages you send to the user. Views are responsible for displaying the data that the Controller has gathered from the Models on the page.
      • +
      + +

      For a far better expanation please see this post.

      + +

      Controllers

      + +

      The tasks controller can be found in the file app/controllers/tasks_controller.rb. In that file there are several different methods, for example:

      +
      # GET /tasks
      +# GET /tasks.json
      +def index
      +  @tasks = Task.all
      +end
      +
      +

      The comments tell you when this action will run. In the case above, it is when someone makes a GET request to /tasks. (How requests map to controllers is set up in config/routes.rb in this case with the line resources :tasks. You can find out more about request routing and routes.rb from the rails routing docs.) All the index action does is to use the Task model to pull all the existing tasks out of the database. Just like sinatra it will use the instance variable @tasks to share the information with a view. By default the view with the same name as the action will be run - in this case views/tasks/index.html.erb.

      + +

      Scaffolding a model with rails generate scaffold will create a controller with the following actions:

      + +
        +
      • index: for listing all the tasks.
      • + +
      • show: for seeing a single task on its own page.
      • + +
      • new: for displaying a form to create a task.
      • + +
      • create: for receiving the post request from the ‘new’ form and storing the new task in the database.
      • + +
      • edit: for displaying a form to edit a task.
      • + +
      • update: for receiving the post request from the ‘edit’ form and updating the task in the database.
      • + +
      • destroy: for destroying the task and removing it from the database.
      • +
      + +

      These are known as CRUD actions, short for ‘create’, ‘read’, ‘update’ and ‘destroy’, and represent the common actions that are generally performed on models. Rails provides a RESTful interface to these actions, by mapping appropriate http requests to the controller through the configuration in routes.rb. You can find more out about this in the rails routing docs but, for now, it’s not really that important.

      +
      Task: +
        +
      1. Read through all the actions in the tasks_contoller.rb.
      2. + +
      3. One-by-one try them out in your browser (e.g. by clicking on the 'show'/'edit'/'destroy' links on the localhost:3000/tasks page)
      4. +
      +
      +
      + + +
      + + +

      Views

      + +

      Your app’s views can be found in app/views. You’ll notice that there are view files for most of the controller actions (all the ones that need them):

      + +
      - app
      +  + assets
      +  + controllers
      +  + helpers
      +  + mailers
      +  + models
      +  - views
      +    + layouts
      +    + tasks
      +      - _form.html.erb
      +      - edit.html.erb
      +      - show.html.erb
      +      - new.html.erb
      +      - index.html.erb
      + +

      (There are also some .json.jbundle files. These are new in Rails 4.0. I think they’re for making your app accessible as a json api.) The _form.html.erb is a partial - a view that is shared by other views, which is why it begins with an underscore. _form.html.erb is used in both the edit.html.erb and new.html.erb views.

      + +

      Layouts

      + +

      Just like Sinatra, Rails allows you to use layout templates to reduce the amount of repetition in your erb files. Rails has even gone so far as to set one up for you. You can have a look at the layout in app/views/layouts/application.html.erb.

      + +

      app/views/layouts/application.html.erb will be used by default by all the views in your application. It is possible to create other layout files (e.g. admin.html.erb) to use with certain views. You can find out more about doing this here.

      + +

      I’m going to add Twitter Bootstrap to the rails app by linking the online version of the css to the top of application.html.erb:

      +
      <!DOCTYPE html>
      +<html>
      +<head>
      +  <title>ProjectManager</title>
      +
      +  !-- Latest compiled and minified CSS -->
      +  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css">
      +
      +  <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
      +  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
      +  <%= csrf_meta_tags %>
      +</head>
      +<body>
      +
      +<%= yield %>
      +
      +</body>
      +</html>
      +
      +

      Where to put CSS and Images

      + +

      In Sinatra you had to put CSS and images in the public folder. Rails has a different way of dealing with these things: you need to put them in app/assets/... This is to allow Rails to use sass: a special language that makes css easier to write and manage. You might want to investigate sass in the future, for now the important thing is that writing css in a sass file is fine - the css will be unchanged and behave as normal.

      + +

      Let’s write some custom CSS in app/assets/css/application.css.scss:

      +
      /*
      + * This is a manifest file that'll be compiled into application.css, which will include all the files
      + * listed below.
      + *
      + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
      + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
      + *
      + * You're free to add application-wide styles to this file and they'll appear at the top of the
      + * compiled file, but it's generally better to create a new file per style scope.
      + *
      + *= require_self
      + *= require_tree .
      + */
      +
      +h1 {color: red;}
      +
      Task: +
        +
      1. Have a look through all the views in app/views/tasks. See if you can work out roughly what they do.
      2. + +
      3. Add Twitter Bootstrap to your site (by editing app/views/layouts/application.html.erb as above).
      4. + +
      5. See if you can change the index.html.erb view so that the table is a Twitter Bootstrap striped table.
      6. + +
      7. See if you can add a Twitter Bootstrap navbar to your site (in layouts/application.html.erb).
      8. + +
      9. Change the colour of the navbar, by adding some custom css to app/assets/css/application.css.scss.
      10. +
      +
      +
      + + +
      + + +

      Rails console

      + +

      Rails provides its own special version of irb known as the rails console. It’s basically irb with your rails project already loaded, so that you can easily interact with the application and the database. You start the console at the command line (in your project_manager folder):

      + +
      $ rails console
      + +

      We’ll use the console to have a closer look at the Task model that was created via the rails generate scaffold.

      + +

      Models

      + +

      If you take a look at the file app/models/task.rb you’ll find the following:

      +
      class Task < ActiveRecord::Base
      +end
      +
      +

      The important bit here is the < ActiveRecord::Base, which is saying that the class inherits from ActiveRecord::Base. ActiveRecord is a ruby library that allows you to access SQL, or relational, databases from ruby (whereas mongoid was for accessing the NoSQL, or document-based, database MongoDB). You’ll note that, unlike mongoid we don’t specify which fields the Task model has - ActiveRecord takes this information automatically from the database. ActiveRecord is similar to mongoid in terms to how you pull things out of the database:

      +
      Task.all     # to find all the tasks
      +
      +# create a new task (not yet in the database)
      +t = Task.new(:name => "Washing up", :due_date => '14/8/2013', :project => 'Housework')
      +
      +# save the task to the database
      +t.save
      +
      +# pull a task out of the database
      +t2 = Task.first
      +
      +# update an attribute
      +t2.completed = true
      +
      +# save the update to the database
      +t2.save
      +
      +

      Adding logic to the model

      + +

      A useful question to be able to ask a Task would be whether it is overdue yet. It is easy to add this logic to the model in app/models/task.rb:

      +
      class Task < ActiveRecord::Base
      +
      +  def overdue?
      +    due_date < Date.today && !completed?
      +  end
      +
      +end
      +
      +

      You can try this out in the rails console (but you need to reload the class to pick up the changes):

      + +
      > reload!
      +> t = Task.last
      +> t.overdue?
      +
      Task: +
        +
      1. Open up irb and try working through the set of operations above to experiment with creating a new Task and saving it to the database via the rails console.
      2. + +
      3. Add the overdue? method to the Task model. Check you use the new method in irb.
      4. +
      +
      +
      + + +
      + + +

      Rails resources

      + +

      We are not going to do much more Rails in class, but I strongly recommend you use it for your project. I’m hoping that the stuff we’ve done with Sinatra will have given you enough of insight to be able to effectively discover rails for yourselves.

      + +

      One resource that you’ll definitely want to have a look at is Railscasts. For most things you’ll want to do in rails there’s a railscast telling you how to do it! They’re really clear and demonstrate exactly where to put stuff in your rails application. Even if you’re not trying to do anything in particular, watching a couple of railscasts is a great way to passively discover more about how rails works. Here are a few you might want to start with:

      + +
        +
      • http://railscasts.com/episodes/417-foundation: an overview of a Twitter Bootstrap - like framework called Foundation.
      • + +
      • http://railscasts.com/episodes/310-getting-started-with-rails: advice on how to get started with rails.
      • + +
      • http://railscasts.com/episodes/360-facebook-authentication: how to integrate facebook log-in into your app.
      • + +
      • http://railscasts.com/episodes/209-introducing-devise: how to easily provide a log-in to your site, using Devise (this is how you should do authentication!) [Warning: old but probably still relevant].
      • + +
      • http://railscasts.com/episodes/328-twitter-bootstrap-basics: a ruby gem to make adding Twitter Bootstrap to your app easier.
      • +
      + +

      RailsApps is a great site with many nice tutorials. There’s also the learn rails book which you can currently get for free, provided you’re willing to give feedback. If you’re using this book I’d recommend starting with Chapters 9 and then 14 (and then flicking back and forth as necessary). It’s well worth working through - it guides you through a mail list signup and management application, including integration with MailChimp.

      + +

      There’s also the Rails Tutorial book by Michael Hartl, which gives a thorough and up-to-date tutorial for building a rails app.

      + +

      Finally, as will all web things, Google is probably your most useful resource for answering most questions!

      + +
      + +
      + +
      + + + + +
      + + + + diff --git a/colophon.html b/colophon.html new file mode 100644 index 0000000..0ace2dd --- /dev/null +++ b/colophon.html @@ -0,0 +1,42 @@ + + + + + + Colophon + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + + +
      + + + + diff --git a/colophon.md b/colophon.md deleted file mode 100644 index 283b259..0000000 --- a/colophon.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -layout: default -title: Colophon ---- diff --git a/contents/index.html b/contents/index.html new file mode 100644 index 0000000..80a454a --- /dev/null +++ b/contents/index.html @@ -0,0 +1,149 @@ + + + + + + Code61 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + + + + +
      + + +

      Course 2

      + +

      Web Fundamentals 2

      + + + +
      + + + + + +
      + + +

      Course 4

      + +

      Further web programming with Ruby

      + + + +
      + +
      + +
      + + + + +
      + + + + diff --git a/course1.html b/course1.html new file mode 100644 index 0000000..63f5ca9 --- /dev/null +++ b/course1.html @@ -0,0 +1,146 @@ + + + + + + Course 1 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +

      Overall aims

      + +
        +
      • Understanding web technologies: hosting, DNS, server-side/client-side distintion
      • + +
      • Basic HTML and CSS
      • + +
      • Git (through github git gui)
      • + +
      • Data submission to a google form
      • + +
      • Basic analytics (through google analytics)
      • + +
      • Deploying site to github pages
      • + +
      • Familiarity with the command line
      • +
      + +

      Sessions

      + +
        +
      • Preparation +
          +
        • Install Chrome
        • + +
        • Install Sublime text
        • + +
        • Create Github account
        • + +
        • Install GitHub for Mac/Windows, (w. ssh keys?)
        • + +
        • Watch DNS videos
        • + +
        • Do GA Project 1
        • +
        +
      • + +
      • Session 1 +
          +
        • Talk through the idea of a web host
        • + +
        • Talk through DNS: the url, the DNS system, how to buy a domain name
        • + +
        • Introduce to HTML and developer tools
        • + +
        • Show how to create file and view it in browser
        • + +
        • HTML exercise
        • + +
        • [hwk] Buy a domain name
        • + +
        • [hwk] Do GA Project 2
        • + +
        • [hwk] Work on own site
        • + +
        • [ext] Intro to command line
        • +
        +
      • + +
      • Session 2 +
          +
        • Explain what git is - multiple versions of files
        • + +
        • Push first_site to github and update
        • + +
        • Introduce to CSS, CSS exercise1
        • + +
        • Introduce to CSS class/id selectors, CSS exercise2
        • + +
        • [hwk?] Publish site using gh_pages
        • + +
        • [hwk] Do GA Project 3
        • + +
        • [hwk] Finish exercises
        • +
        +
      • + +
      • Session 3 +
          +
        • CSS in a separate file, different resource refs, CSS exercise
        • + +
        • https://www.inkling.com/read/dreamweaver-cs6-missing-manual-david-sawyer-mcfarland-1st/chapter-4/understanding-links
        • + +
        • Twitter bootstrap, bootstrap exercise
        • + +
        • [hwk] Finish bootstrap exercise
        • + +
        • [hwk] Point domain name to first_site
        • +
        +
      • + +
      • Session 4 +
          +
        • Google analytics - just how to put in the snippet and an example
        • + +
        • Form submissions
        • + +
        • Submitting to a google form
        • + +
        • [hmk] Finish (add google analytics) and submit first_site
        • +
        +
      • +
      + + + +
      + + + + diff --git a/course1.md b/course1.md deleted file mode 100644 index c9649d6..0000000 --- a/course1.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Course 1 -layout: default ---- - -## Overall aims - -+ Understanding web technologies: hosting, DNS, server-side/client-side distintion -+ Basic HTML and CSS -+ Git (through github git gui) -+ Data submission to a google form -+ Basic analytics (through google analytics) -+ Deploying site to github pages -+ Familiarity with the command line - -## Sessions - -- [Preparation](c1prep) - + Install Chrome - + Install Sublime text - + Create Github account - + Install GitHub for Mac/Windows, (w. ssh keys?) - + Watch DNS videos - + Do GA Project 1 -- [Session 1](c1s1) - + Talk through the idea of a web host - + Talk through DNS: the url, the DNS system, how to buy a domain name - + Introduce to HTML and developer tools - + Show how to create file and view it in browser - + HTML exercise - + [hwk] Buy a domain name - + [hwk] Do GA Project 2 - + [hwk] Work on own site - + [ext] Intro to command line -- [Session 2](c1s2) - + Explain what git is - multiple versions of files - + Push first_site to github and update - + Introduce to CSS, CSS exercise1 - + Introduce to CSS class/id selectors, CSS exercise2 - + [hwk?] Publish site using gh_pages - + [hwk] Do GA Project 3 - + [hwk] Finish exercises -- [Session 3](c1s3) - + CSS in a separate file, different resource refs, CSS exercise - + https://www.inkling.com/read/dreamweaver-cs6-missing-manual-david-sawyer-mcfarland-1st/chapter-4/understanding-links - + Twitter bootstrap, bootstrap exercise - + [hwk] Finish bootstrap exercise - + [hwk] Point domain name to first_site -- [Session 4](c1s4) - + Google analytics - just how to put in the snippet and an example - + Form submissions - + Submitting to a google form - + [hmk] Finish (add google analytics) and submit first_site - - - diff --git a/course2.html b/course2.html new file mode 100644 index 0000000..898435d --- /dev/null +++ b/course2.html @@ -0,0 +1,92 @@ + + + + + + Course 2 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +

      Overall aims

      + +
        +
      • to get lots more practice with HTML and CSS
      • + +
      • to learn about and practice using git for collaboration
      • + +
      • to meet jquery - mostly as a DOM manipulation/special effects tool, rather than covering javascript as a programming language
      • + +
      • to meet the command line and start getting comfortable moving around, trying git etc.
      • +
      + +

      Sessions

      + +
        +
      • +

        Preparation

        + +
          +
        • Rails installer to get the bash/windows emulator??
        • +
        +
      • + +
      • +

        Session 1

        + +
          +
        • Collaboration with git
        • + +
        • Revision - create a site in a group
        • +
        +
      • + +
      • +

        Session 2

        + +
          +
        • Introducing jQuery
        • +
        +
      • + +
      • +

        Session 3

        +
      • + +
      • +

        Session 4

        +
      • +
      + + + +
      + + + + diff --git a/course2.md b/course2.md deleted file mode 100644 index 790af36..0000000 --- a/course2.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Course 2 -layout: default ---- - -## Overall aims - -+ to get lots more practice with HTML and CSS -+ to learn about and practice using git for collaboration -+ to meet jquery - mostly as a DOM manipulation/special effects tool, rather than covering javascript as a programming language -+ to meet the command line and start getting comfortable moving around, trying git etc. - -## Sessions - -- [Preparation](c2prep) - + Rails installer to get the bash/windows emulator?? - -- [Session 1](c2s1) - + Collaboration with git - + Revision - create a site in a group - -- [Session 2](c2s2) - + Introducing jQuery - -- [Session 3](c2s3) - -- [Session 4](c2s4) - diff --git a/course3.html b/course3.html new file mode 100644 index 0000000..d9ad741 --- /dev/null +++ b/course3.html @@ -0,0 +1,124 @@ + + + + + + Course 3 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +

      Sessions

      + +
        +
      • Preparation +
          +
        • Install ruby
        • + +
        • Check your ruby installation
        • + +
        • Change sublime text settings
        • + +
        • [hwk] Codecademy ruby 1 & 2
        • +
        +
      • + +
      • Session 1 +
          +
        • Ruby as an interpreted language, irb, comments
        • + +
        • Concept of a value and an expression
        • + +
        • Try it in irb exercise: simple numbers and strings
        • + +
        • Introduction to ruby names and variables
        • + +
        • String interpolation
        • + +
        • Install sinatra with ruby gems, simple sinatra example
        • + +
        • Sinatra with matchers
        • + +
        • [hwk] Modify example to use string operations
        • + +
        • [ext] Look at tests
        • + +
        • [hwk] heroku account, ssh setup
        • +
        +
      • + +
      • Session 2 +
          +
        • Start with basic app using a post request and a conditional
        • + +
        • Show them how to deploy it, diagram explaining remotes?
        • + +
        • Improving with templates and erb, redeploy
        • + +
        • Boolean ops, Truthy and falsey
        • + +
        • Modify their app to use more form information
        • + +
        • Sinatra templates, erb
        • + +
        • Deploying
        • + +
        • [hwk] FOAAS? - practices templates
        • + +
        • [hwk] Codecademy ruby 3 & 4
        • +
        +
      • + +
      • Session 3 +
          +
        • Arrays, iterating
        • +
        + +
          +
        • Reading in from a CSV file
        • + +
        • Iterating in a template
        • +
        +
      • + +
      • Session 4 +
          +
        • sending emails?
        • + +
        • Hashes
        • +
        +
      • +
      + + + +
      + + + + diff --git a/course3.md b/course3.md deleted file mode 100644 index 33523dc..0000000 --- a/course3.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Course 3 -layout: default ---- - -## Sessions - -- [Preparation]() - + Install ruby - + Check your ruby installation - + Change sublime text settings - + [hwk] Codecademy ruby 1 & 2 -- [Session 1](c3s1) - + Ruby as an interpreted language, irb, comments - + Concept of a value and an expression - + Try it in irb exercise: simple numbers and strings - + Introduction to ruby names and variables - + String interpolation - + Install sinatra with ruby gems, simple sinatra example - + Sinatra with matchers - + [hwk] Modify example to use string operations - + [ext] Look at tests - + [hwk] heroku account, ssh setup -- [Session 2](c3s2) - + Start with basic app using a post request and a conditional - + Show them how to deploy it, diagram explaining remotes? - + Improving with templates and erb, redeploy - + Boolean ops, Truthy and falsey - + Modify their app to use more form information - + Sinatra templates, erb - + Deploying - + [hwk] FOAAS? - practices templates - + [hwk] Codecademy ruby 3 & 4 -- [Session 3](c3s3) - + Arrays, iterating - - + Reading in from a CSV file - + Iterating in a template -- [Session 4](c3s4) - + sending emails? - + Hashes diff --git a/course4.html b/course4.html new file mode 100644 index 0000000..77da6d7 --- /dev/null +++ b/course4.html @@ -0,0 +1,92 @@ + + + + + + Course 4 + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +

      Overall aims

      + +

      Sessions

      + +
        +
      • +

        Preparation

        +
      • + +
      • +

        Session 1

        + +
          +
        • functions: defining, calling
        • + +
        • lots of exercises with tests
        • + +
        • [hwk] refactor a sinatra app
        • +
        +
      • + +
      • +

        Session 2

        + +
          +
        • more functions
        • + +
        • moving towards classes
        • + +
        • maybe just do classes?
        • +
        +
      • + +
      • +

        Session 3

        + +
          +
        • mongodb/classes
        • +
        +
      • + +
      • +

        Session 4

        + +
          +
        • CRUD app
        • +
        +
      • +
      + + + +
      + + + + diff --git a/course4.md b/course4.md deleted file mode 100644 index 4bea721..0000000 --- a/course4.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Course 4 -layout: default ---- - -## Overall aims - - -## Sessions - -- [Preparation](c4prep) - -- [Session 1](c4s1) - + functions: defining, calling - + lots of exercises with tests - + [hwk] refactor a sinatra app -- [Session 2](c4s2) - + more functions - + moving towards classes - + maybe just do classes? -- [Session 3](c4s3) - + mongodb/classes -- [Session 4](c4s4) - + CRUD app \ No newline at end of file diff --git a/extras/index.html b/extras/index.html new file mode 100644 index 0000000..91f20d9 --- /dev/null +++ b/extras/index.html @@ -0,0 +1,594 @@ + + + + + + Extras + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + +
      + + +
      + + +
      + + +

      Recap from last time

      + +

      Before you start: updating gitgit

      + +

      There have been some updates and improvements to gitgit! To get these improvements open the command line and run:

      + +
      gem update gitgit
      + +

      To check it worked run

      + +
      gitgit version
      + +

      it should say ‘0.0.5’ (or higher).

      + +

      Before you start: verifying github email address

      + +

      Today we’re going to be putting up your first site using GitHub Pages - a free hosting solution provided by GitHub.

      + +

      In order for this to work you need to have verified your email address with GitHub.

      +
      Task: +
        +
      1. Log into GitHub.
      2. +
      3. If you see a warning at the top that you haven't verified your +email address, follow the instructions to do that now.
      4. +
      5. If not, you're good to go!
      6. +
      +
      +

      Review exercise

      +
      Task: +
        +
      1. Open the comand line
      2. +
      3. Navigate to your 'first_site' folder (cd/ls)
      4. +
      5. Open 'first_site/index.html' in Sublime Text
      6. +
      7. Make a change to the file
      8. +
      9. Save the changes and push to github ("gitgit save", "gitgit +push")
      10. +
      11. Log into github and check you can see your changes
      12. +
      + +
      +

      Something new: publishing site using GitHub pages

      + +

      You’re now going to publish your ‘first_site’ using GitHub Pages.

      + +

      To do this you need to push your website up to a branch called ‘gh-pages’. You don’t know about branches yet, but you can see them on github. Right now you’ll just see a single branch called ‘master’.

      + +

      You don’t actually need to understand anything about branches at the moment, as gitgit makes it really easy to publish as a github page. Just run

      + +
      gitgit publish
      + +

      When you go to github you should now see a ‘gh-pages’ option in the branches dropdown.

      + +

      The ‘gh-pages’ branch is a signal to github that you want your code to be deployed as a website. You can find the url of your website by looking in your repository settings on GitHub.

      + +
      + + +
      + + +

      Wiring up your domain

      + +

      Getting your domain name to point to your GitHub Page

      + +

      The point of this exercise is to set up your domain name to point towards your new GitHub pages site.

      + +

      As GitHub hosts many different pages at their IP address, it isn’t quite as simple as pointing your domain address towards that IP address. There are two things you need to do to get your domain name working with your GitHub pages site:

      + +
        +
      1. Tell your domain registrar (e.g 123-reg or godaddy) to point your domain name towards GitHub’s IP address.
      2. + +
      3. Tell GitHub that requests to your domain name should come to your site.
      4. +
      + +

      Github explains this here.

      + +

      Pointing your domain name towards GitHub

      + +

      For the first bit you need to log in to your domain registrar and change the DNS settings. You want an A-record pointing to 204.232.175.78 (which is github.com). Note that it can take up to a couple of days for DNS changes to propagate.

      + +

      If you’re using 123-reg, your should log in, select your domain from the list, and click “Manage”. You should then go to “Manage DNS”.

      + +

      123-reg DNS Settings

      + +

      (The @ dns entry stands for the root or bare domain.)

      +
      Task: + +

      Log in to your domain registrar and set an A-record to point towards GitHub.

      + +
      +

      Your changes won’t take effect immediately.

      + +

      Tell github to expect requests for your domain name

      +
      Task: +
        +
      1. +

        Open Sublime Text and create a new file.

        +
      2. + +
      3. +

        Write your domain name on the first line of the new file e.g:

        + +
          mydomain.com
        +
      4. + +
      5. +

        Save that file as CNAME (uppercase, with no extension) in your first_site folder

        +
      6. + +
      7. +

        Commit your change and then push to github.

        +
      8. +
      +
      +
      + + +
      + + +

      GitHub account

      + +

      Git is a program that helps with the management of code. It means that you completely avoid the situation where you end up with files called team_contacts_v1, team_contacts_v2 etc. It also allows you to share your code with others and collaborate on code in an efficient way.

      + +

      GitHub is a site that makes sharing code part of git really easy. It is the go-to choice both for startups and open-source software projects. (There are several other sites that are similar to GitHub e.g. BitBucket, but GitHub is the most widely used.)

      + +

      GitHub also allows you to put a static website online for free, using GitHub Pages. We will be making use of this feature during the course.

      +
      Task: + +

      Sign up for a GitHub account at https://github.com/. Make sure you know your password to avoid awkward moments in class!

      + +
      +
      + + +
      + + +

      Meet the Command Line

      + +

      The command line is a way to interact with your computer programmatically. If you are doing any software development you will need to get to grips with using the command line, as many of the programs you will use will be run from the it, instead of by clicking an icon.

      + +

      Opening the command line

      + +
        +
      • On a Mac open Terminal (Applications > Terminal)
      • + +
      • On Windowns open Command Prompt with Ruby on Rails
      • +
      + +

      Moving around

      + +

      Note: when giving you instructions for the command line we will precede them with a $ to represent the command prompt e.g.

      + +
      $ some_command
      + +

      You shouldn’t type the $ sign - just the stuff after it. So for the above instruction you would just type some_command into the command line.

      + +

      The first thing you will need to get used to is moving around. Start by printing the name of the directory you are in:

      + +
      $ pwd
      + +

      Then have a look at what’s in that directory ( list the contents):

      + +
      $ ls
      + +

      To move up a directory ( change directory ) do

      + +
      $ cd ..
      + +

      To move back into the folder you just left do

      + +
      $ cd name_of_the_folder
      + +

      Your commandline will help you: tab can often be used to auto-complete names of files, the up arrow can be used to cycle through previous commands that you have typed.

      + +

      Creating a directory

      + +

      You can do a lot more on the command line than just move around. We’ll be using the command line a lot over the course. For the time being we just need to create a folder:

      + +
      $ mkdir coding_course
      + +

      Note: choosing names without spaces makes command line navigation easier.

      +
      Task: +
        +
      1. +

        Open your command line:

        + +
          +
        • On a Mac open Terminal (Applications > Terminal)
        • + +
        • On Windowns open Command Prompt with Ruby on Rails
        • +
        +
      2. + +
      3. +

        Find out where you are:

        + +
         $ pwd
        +
      4. + +
      5. +

        See what is in the same folder:

        + +
         $ ls
        +
      6. + +
      7. +

        If you are on a Mac move into Documents:

        + +
         $ cd Documents
        +
      8. + +
      9. +

        Create the folder for the coding course:

        + +
         $ mkdir coding_course
        +
      10. + +
      11. +

        Move into that folder:

        + +
         $ cd coding_course
        +
      12. + +
      13. +

        Move back up to the folder above

        + +
         $ cd ..
        +
      14. + +
      15. +

        Move back into the coding course folder. This time don't type out coding_course - just type out the first few letters and hit Tab:

        + +
        $ cd coding_course
        +
      16. + +
      17. +

        In the Finder (Mac) or My Computer (Windows) find the folder that you just created.

        +
      18. +
      +
      +
      + + +
      + + +

      Ruby and Git

      + +

      In order to save to github you’ll need a program called git on your laptop. To make git easier we’ll be using a program called gitgit. To run gitgit you need ruby installed, so in this step we’ll install that too.

      + +

      On Windows

      + +

      On Windows the guys at Rails Installer have put together a single package that contains both ruby and git. We’re going to use that to get both on your laptop.

      +
      Task: +

      If you are on Windows:

      + + +
      +

      On a Mac

      + +

      Macs come with ruby already installed, so you don’t have to worry about getting ruby!

      + +

      To install git we’re going to use a tool called Homebrew, which helps install open source software to a mac.

      +
      Task: +
        +
      • Open Terminal (Applications > Utilities > Terminal).
      • + +
      • Follow the installation instructions on the Homebrew site. It will ask you to copy and paste something like
      • +
      +
      
      +ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
      +
      +

      into the Terminal. (You should check this, as the precise instructions might have changed.)

      + +
        +
      • +

        Once homebrew in installed type the following into the Terminal:

        + +
          brew install git
        +
      • +
      +
      +
      + + +
      + + +

      Pushing to GitHub

      + +

      Git is a version control system. It allows you to keep the entire history of your code, and makes it easy to share and collaborate with others.

      + +

      Using git

      + +

      Using git is really easy:

      + +
        +
      1. Set up a folder to be a git repo. This tells git to track all changes in that folder.
      2. + +
      3. After you’ve made some changes, save them into the repository.
      4. + +
      5. Once you’ve saved the changes push them up to github.
      6. +
      + +

      The first point is important: git works on a folder level. It tracks all the changes you make to files within a given folder.

      + +

      Actually using git

      + +

      Actually using git is a bit harder. It’s a very powerful tool and pretty complex to get started with. To make things simpler, we’re going to use a tool called gitgit.

      + +

      To install gitgit open the command line and type the following:

      + +
      gem install gitgit
      + +

      To see if this worked, type

      + +
      gitgit
      + +

      You should see a list of gitgit commands something like this:

      + +
      $ gitgit
      +Commands:
      +  gitgit help [COMMAND]  # Describe available commands or one specific command
      +  gitgit init            # Initialise a git repo
      +  gitgit lg              # Show your recent saves
      +  gitgit push            # Push your changes to github
      +  gitgit save            # Save you changes to the repo
      +  gitgit status          # See what changes you've made since you last save
      + +

      If it didn’t work, you might need to do

      + +
      sudo gem install gitgit
      + +

      and type your password.

      + +

      You also might need to do

      + +
      rbenv rehash
      + +

      If in doubt contact a teaching assistant!

      + +

      Using gitgit

      + +

      To make a folder into a git repository:

      + +
      gitgit init
      + +

      then follow the instructions. You’ll only need to do this once for each folder you want to make into a repository.

      + +

      After you’ve made some changes to your files and saved them, you can save them into your repo by typing:

      + +
      gitgit save
      + +

      Finally, to push your code up to github you can do

      + +
      gitgit push
      + +

      Before you do this, you will need to setup your repo with github.

      + +

      Setting up your repo with github

      + +

      Go to github, login, and click “Create New Repo” in the top left hand corner.

      + +

      Creating a repo on GitHub

      + +

      Follow the instructions, calling it something like first_site. Do not click the box which says ‘Create a readme with this repository’. You’ll get to a page when it’ll describe how to get your code online. You want to follow the instructions for “Pushing an existing repository to github”.

      + +

      Pushing your code to github

      + +

      We will now set up your first_site folder to use git and push it up to github.

      +
      Task: +
        +
      1. Navigate to your first_site folder using cd and ls.
      2. +
      3. Make it into a git repo: "gitgit init"
      4. +
      5. Save all the work you've done so far: "gitgit save"
      6. +
      7. Log in to GitHub.
      8. +
      9. On github create a new repository called 'first_site'. DO NOT click the box which says 'Create a readme'.
      10. +
      11. Copy and paste the instructions it gives you into the command line. You are 'Pushing an existing repository to github'.
      12. +
      13. Go back to github and refresh the page. You should see your code.
      14. +
      +
      +
      + + +
      + + +

      Configuration variables

      + +

      The purpose of this next part is to add an email notification to the sign-up form you worked on last time.

      + +

      Problem: where to store the password

      + +

      In the example email script you were prompted for your gmail username and password. This meant we side-stepped the issue of where to write this (sensitive) information down.

      + +

      The problem of where in your program to store sensitive, application-specific configuration data is one that you will come across often. For example, you may want to store:

      + +
        +
      • An email username/password for your app.
      • + +
      • Database configuration, username and passwords.
      • + +
      • Amazon webservices api tokens and secret key (e.g. Amazon S3 etc.).
      • + +
      • Facebook integration token and key.
      • + +
      • GitHub integration token and key.
      • + +
      • … tokens and keys to connect to many other services.
      • +
      + +

      Quite often these keys will have different values in different environments: you probably won’t want to use your live production database when developing or testing.

      + +

      A tempting (but non-ideal) place to put this information is in the code in your git repository (i.e. just write them into the source code files). This is bad for a few reasons including:

      + +
        +
      1. Anyone with access to your git repository has access to your email password etc.
      2. + +
      3. It’s hard to manage different versions for different environment - you will need to remember to replace your development info with your production info everytime before you do a ‘git push heroku’.
      4. +
      + +

      In general it is bad practice to put passwords/tokens/keys in your git repo.

      + +

      Using ENV variables

      + +

      A good solution for this situation is to use environment variables. All ruby programs have access to an ENV hash containing options from the environment where the program is run. You can see the environment variables set on your computer by running

      + +
      $ env
      +TERM_PROGRAM=Apple_Terminal
      +SHELL=/bin/bash
      +TERM=xterm-256color
      +...
      + +

      You can then check that you can access these in irb:

      +
      > ENV['SHELL']
      +#=> "/bin/bash"
      +
      +

      We are going to store the configuration values (e.g. email username and password) as environment variables for our program. Heroku makes it easy for you to manage ENV variables on their servers, as described here. To replicate the situation on your laptop you can use a gem called dotenv.

      + +

      You can install dotenv via rubygems. If you use rbenv (i.e. if you followed ‘The Hard Way’ installation instructions) you will then need to do a rbenv rehash. (This is because the foreman gem comes with a command line tool, which we need to tell rbenv about.)

      + +
      gem install dotenv
      +
      # in .env
      +GMAIL_USER_NAME=yourgmailusername
      +GMAIL_PASSWORD=password12345
      +
      +

      You can then access these variables in your ruby program by the ENV hash:

      +
      user_name = ENV['GMAIL_USER_NAME']
      +password = ENV['GMAIL_PASSWORD']
      +
      +

      In order to keep your .env configuration secret you need to make sure it doesn’t get added to the git repo. If you want to deploy to Heroku, it is also important that your Procfile isn’t in your git repo (otherwise it will mess with Heroku’s settings when it gets up there). To do this you need to make sure both of them are in your .gitignore:

      +
      # in .gitignore
      +Procfile
      +.env
      +
      Task: +
        +
      1. +

        Fetch down the changes to mongo1. In the mongo1 directory:

        + +
         $ git fetch
        +
      2. + +
      3. +

        Checkout the email branch:

        + +
         $ git checkout email
        + +

        This has the solution from last time along with some email examples. If you spent a lot of time making your solution from last session look nice, you might instead want to merge the email branch into your master - up to you!

        +
      4. + +
      5. +

        Do a bundle install (and a rbenv rehash if necessary):

        + +
         $ bundle install
        + $ rbenv rehash
        +
      6. + +
      7. +

        Copy the contents of mongo1/example_app/Procfile.sample and mongo1/example_app/.env.sample and save them as mongo1/example_app/Procfile and mongo1/example_app/.env filling in your gmail details in .env.

        +
      8. + +
      9. +

        Start the app with foreman start. Check that the app sends you a fruity email.

        +
      10. +
      +
      +

      ENV variables on heroku

      + +

      As the settings in .env aren’t in the git repo, they won’t be pushed to heroku. You will need to set these variables separately. Heroku makes it easy to do this. Assuming your app is already on heroku you can set environment variables as:

      + +
          $ heroku config:set GMAIL_USER_NAME=yourgmailusername
      +    $ heroku config:set GMAIL_PASSWORD=password12345
      + +

      You can check the values you have set by running

      + +
          $ heroku config
      + +

      There are other tools you can use to manage heroku configuration variables, which might be useful if you end up setting a lot of options. See here for more details.

      + +
      + +
      + +
      + + + + +
      + + + + diff --git a/index.html b/index.html index 94b9ab3..9bc8f67 100644 --- a/index.html +++ b/index.html @@ -1,11 +1,47 @@ ---- -layout: default -title: code61 - Learn to code -cssclass: homepage ---- - -
      - + + + + + + code61 - Learn to code + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + + + + +
      + + + + diff --git a/overview.html b/overview.html new file mode 100644 index 0000000..95caed1 --- /dev/null +++ b/overview.html @@ -0,0 +1,94 @@ + + + + + + Overview + + + + + + + + + + + + + + + + + + + + + + + + + + +
      + + +

      Give students enough to get a first working prototype, upon which they can build.

      + +

      4 course

      + +
        +
      • Course 1: Personal site: How to put up a basic static site +
          +
        • Understanding web technologies: hosting, DNS, server-side/client-side distintion
        • + +
        • Basic HTML and CSS
        • + +
        • Git (through github git gui)
        • + +
        • Data submission to a google form
        • + +
        • Basic analytics (through google analytics)
        • + +
        • Deploying site to github pages
        • +
        +
      • + +
      • Course 2: jquery + git collaboration +
          +
        • How to collaborate using git (still using github git gui)
        • + +
        • Mostly following codecademy jquery tutorial
        • + +
        • consuming lastFM api?
        • +
        +
      • + +
      • Course 3: Intro to ruby +
          +
        • Basic ruby programming: variables, numbers, strings
        • + +
        • Motivated by simple sinatra apps
        • + +
        • conditionals, functions, arrays, hashes, iteration
        • +
        +
      • + +
      • Course 4: Intro to ruby 2 +
          +
        • Slightly more advanced ruby: classes
        • + +
        • Interacting with a database
        • + +
        • Rubygems/libraries e.g. Sending email?
        • +
        +
      • +
      + + + +
      + + + + diff --git a/overview.md b/overview.md deleted file mode 100644 index 525b4e4..0000000 --- a/overview.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Overview -layout: default ---- - -Give students enough to get a first working prototype, upon which they can build. - -4 course - -- [Course 1: Personal site](course1): How to put up a basic static site - + Understanding web technologies: hosting, DNS, server-side/client-side distintion - + Basic HTML and CSS - + Git (through github git gui) - + Data submission to a google form - + Basic analytics (through google analytics) - + Deploying site to github pages -- [Course 2: jquery + git collaboration](course2) - + How to collaborate using git (still using github git gui) - + Mostly following codecademy jquery tutorial - + consuming lastFM api? -- [Course 3: Intro to ruby](course3) - + Basic ruby programming: variables, numbers, strings - + Motivated by simple sinatra apps - + conditionals, functions, arrays, hashes, iteration -- [Course 4: Intro to ruby 2](course4) - + Slightly more advanced ruby: classes - + Interacting with a database - + Rubygems/libraries e.g. Sending email?