Skip to content

Commit 84152da

Browse files
committed
Updated c4s3
1 parent 1ec7ff2 commit 84152da

15 files changed

+626
-142
lines changed

_sessions/c4s2/3_setters.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,12 @@ c.age #=> 7
4141
{% exercise %}
4242
Update your solution in `person.rb` to allow the `first_name` and `last_name` to be set independently, and have the `name` update accordingly:
4343
{%highlight ruby %}
44-
p = Person.new("Tom Close")
45-
p.name #=> "Tom Close"
44+
p = Person.new({:name => "Bart Simpson", :dob => "15/1/1990"})
4645

47-
p.first_name = "Thomas"
48-
p.name #=> "Thomas Close"
46+
p.name #=> "Bart Simpson"
47+
48+
p.first_name = "Bartholomew"
49+
p.name #=> "Bartholomew Simpson"
4950
{% endhighlight %}
5051
You might need to make changes to which attributes your class stores, to make this work.
5152

_sessions/c4s2/5_homework.md

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,74 @@ title: Homework
1212
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:
1313

1414
- [http://phrogz.net/programmingruby/tut_classes.html](http://phrogz.net/programmingruby/tut_classes.html)
15-
- [http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/](http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/)
15+
- [http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/](http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/)
16+
17+
## Getting set up with MongoDB
18+
19+
Next session we will look at storing information in a database. The database we'll be using is [MongoDB](http://www.mongodb.org/).
20+
21+
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.
22+
23+
The preparation falls into four parts:
24+
25+
1. Install MongoDB.
26+
2. Start running the database.
27+
3. Install the gems to allow ruby to connect to MongoDB.
28+
4. Test your installation.
29+
30+
We will look at these parts separately.
31+
32+
### Install MongoDB
33+
34+
If you installed `homebrew` ("The Hard Way", Mac only), your task is now easy. At the command line write:
35+
36+
brew install mongo
37+
38+
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.
39+
40+
{% exercise %}
41+
Install MongoDB either via
42+
43+
$ brew install mongo
44+
45+
or by downloading and installing from the [MongoDB website](http://www.mongodb.org/downloads).
46+
{% endexercise %}
47+
48+
### Start MongoDB running
49+
50+
You can start MongoDB running from the command line:
51+
52+
$ mongod
53+
54+
You will need to **keep this command line open** and open a new one to continue the instructions.
55+
56+
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.
57+
58+
{% exercise %}
59+
1. Start MongoDB:
60+
61+
$ mongod
62+
63+
2. Check the service is running at [localhost:28017](http://localhost:28017/).
64+
{% endexercise %}
65+
66+
### Install the gems and test
67+
68+
I've set up a project with the gems you need, so this should be straightforward:
69+
70+
{% exercise %}
71+
1. Clone the project:
72+
73+
$ git clone https://github.com/code61/mongo_test.git
74+
75+
2. Move into that folder and install the gems:
76+
77+
$ cd mongo_test
78+
$ bundle install
79+
80+
3. Test your installation:
81+
82+
$ ruby main.rb
83+
84+
If you see the text "Everything worked ok!", you're good to go!
85+
{% endexercise %}

_sessions/c4s3/1_intro_to_mongo.md

Lines changed: 98 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,6 @@
22
title: About MongoDB
33
---
44

5-
{% exercise %}
6-
Clone the code for this session:
7-
8-
$ git clone https://github.com/code61/mongo1.git
9-
10-
{% endexercise %}
115

126
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.
137

@@ -20,6 +14,69 @@ MongoDB is one of many different databases that we could have chosen. We went wi
2014

2115
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.
2216

17+
### Using Mongoid
18+
19+
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:
20+
21+
{% highlight ruby %}
22+
class Athlete
23+
include Mongoid::Document
24+
25+
field :name, type: String
26+
field :country, type: String
27+
field :age, type: Integer
28+
field :height, type: Integer
29+
field :weight, type: Integer
30+
field :sex, type: String
31+
field :dob, type: Time
32+
field :gold, type: Integer
33+
field :silver, type: Integer
34+
field :bronze, type: Integer
35+
field :sport, type: Integer
36+
field :events, type: Array
37+
38+
def total_medals
39+
bronze + silver + bronze
40+
end
41+
end
42+
{% endhighlight %}
43+
44+
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:
45+
46+
* `include Mongoid::Document`: this activates this class as a mongoid-enabled class.
47+
* 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.
48+
49+
You can use this class like this:
50+
{% highlight ruby %}
51+
a = Athlete.new
52+
a.name = "Michael Phelps"
53+
a.country = "US"
54+
a.sport = "Swimming"
55+
a.gold = 2
56+
a.silver = 2
57+
a.bronze = 0
58+
59+
a.name #=> "Michael Phelps"
60+
a.total_medals #=> 4
61+
{% endhighlight %}
62+
63+
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:
64+
65+
{% highlight ruby %}
66+
# Let's save Michael in the database
67+
a.save #=> true
68+
69+
# How many athletes do we have?
70+
Athlete.count #=> 1
71+
72+
# Let's pull Michael out again
73+
a = Athlete.first #=> #<Athlete _id: 5315dec6de9c928a02001c9c, name: "Michael Phelps", country: "US", gold: 2, silver: 2, bronze: 0, sport: "Swimming">
74+
75+
# or
76+
a = Athlete.find_by(:name => "Michael Phelps") #=> #<Athlete _id: 5315dec6de9c928a02001c9c, name: "Michael Phelps", country: "US", gold: 2, silver: 2, bronze: 0, sport: "Swimming">
77+
78+
{% endhighlight %}
79+
2380

2481
### Starting MongoDB
2582

@@ -31,35 +88,47 @@ You will need to keep this command line open and continue the instructions in a
3188

3289
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.
3390

34-
### Using it in ruby
91+
{% exercise %}
92+
1. Start MongoDB running on your laptop.
93+
1. Clone down the code for the session: [https://github.com/code61/sinatra_c4s3](https://github.com/code61/sinatra_c4s3)
94+
2. Run `bundle install` to get the required gems.
95+
3. Open up `irb`.
96+
4. Type `require './utils'` (this loads in the `Athlete` class and sets up your MongoDB connection).
97+
5. Try the following
98+
{% highlight ruby %}
99+
a = Athlete.new
100+
a.name = "Michael Phelps"
101+
a.country = "US"
102+
a.sport = "Swimming"
103+
a.gold = 2
104+
a.silver = 2
105+
a.bronze = 0
35106

36-
To interface with MongoDB from ruby we will be using the [Mongoid](http://mongoid.org/) gem. You should have installed the gem already, but if not,
107+
a.name
108+
a.country
37109

38-
$ gem install mongoid
110+
a.save
39111

40-
should do the trick.
112+
Athlete.count
113+
b = Athlete.first
41114

42-
We then need to set some configuration options in our ruby project. Among other things this tells the project which of the mongodb databases on your computer to use - usually you'd want each project to have its own database. The following configuration options should go in a `mongoid.yml` file:
115+
b.name
116+
b.name = "Tom Close"
43117

44-
{% highlight yaml %}
45-
development:
46-
sessions:
47-
default:
48-
hosts:
49-
- localhost:27017
50-
database: mongo_examples
51-
options:
52-
raise_not_found_error: false
53-
{% endhighlight %}
118+
a.name # has this updated?
54119

55-
You then need to include the following code in your `app.rb` (or similar) file:
120+
b.save
121+
a.name # has it updated now?
56122

57-
{% highlight ruby %}
58-
require 'mongoid'
59-
require 'json'
123+
a.reload
124+
a.name
60125

61-
Mongoid.load!("mongoid.yml", :development)
62-
{% endhighlight %}
63-
64-
We've seen the `require` statements before - they just tell ruby that we'd like to use the `mongoid` library (and also `json`). The line `Mongoid.load!("mongoid.yml", :development)` tells `mongoid` where to find the configuration options. The `:development` bit refers to our environment - you will probably want to have different configuration options when you're deploying your app to heroku; mongoid allows this by specifying `:production` and `:development` environments.
126+
# different way of creating an athlete, using a hash
127+
c = Athlete.new(:name => "Chad Le Clos", :country => "South Africa",
128+
:sport => "Swimming", :gold => 1,
129+
:silver => 1, :bronze => 0 )
130+
c.save
65131

132+
d = Athlete.find_by(:name => "Chad Le Clos")
133+
{% endhighlight %}
134+
{% endexercise %}

_sessions/c4s3/2_mongo_classes.md

Lines changed: 0 additions & 63 deletions
This file was deleted.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
title: Searching and sorting
3+
---
4+
5+
One thing that databases are good at is searching for records. Mongoid allows you to search for records in various different ways:
6+
7+
{% highlight ruby %}
8+
Athlete.find_by(:name => "Michael Phelps")
9+
10+
Athlete.find_by(:gold => 2) # returns the first one it finds
11+
12+
Athlete.where(:gold => 2) # returns a 'collection' with all of them
13+
14+
# you can do lots of things with collections e.g. counting
15+
Athlete.where(:gold => 2).count
16+
# or iterating
17+
Athlete.where(:gold => 2).each do |a|
18+
puts a.name
19+
end
20+
# or summing
21+
Athlete.where(:gold => 2).sum(:age)
22+
# or turn it into an array
23+
Athlete.where(:gold => 2).to_a
24+
25+
# searching on multiple things at once
26+
Athlete.where(:gold => 2, :bronze => 3)
27+
# or
28+
Athlete.where(:gold => 2).where(:bronze => 0)
29+
30+
# searching on conditions
31+
Athlete.where(:gold.gte => 2)
32+
33+
{% endhighlight %}
34+
35+
You can find further examples in the [Mongoid docs](http://mongoid.org/en/mongoid/docs/querying.html#queries).
36+
37+
### Sorting
38+
39+
You can also get the database to return things to you sorted:
40+
41+
{% highlight ruby %}
42+
43+
# these both return collections
44+
Athlete.order_by(:age.asc)
45+
Athlete.order_by(:age.desc)
46+
47+
# you can then do things like
48+
# .. take the first 1
49+
Athlete.order_by(:age.asc).first
50+
51+
# .. or the first 10
52+
Athlete.order_by(:age.asc).limit(10).to_a
53+
54+
{% endhighlight %}
55+
56+
57+
{% exercise %}
58+
1. Open `irb` and do `require './utils'`.
59+
2. Call the function `load_athletes`. This loads in all the athletes from London 2012.
60+
3. Answer the following questions:
61+
1. How many athletes were there?
62+
2. How many women? How many men?
63+
3. Who was the oldest athlete?
64+
4. Who was the youngest?
65+
4. How many people won at least 1 gold?
66+
5. What was the average age? (Your answer should have decimal places..)
67+
6. Who got the most golds?
68+
7. Who was the 10th oldest athlete?
69+
{% endexercise %}

0 commit comments

Comments
 (0)