Tumgik
nishacodes 8 years
Link
5 notes View notes
nishacodes 10 years
Text
Using Reduce (aka Inject) in Ruby
Oh, hai there. Have you been missing my Ruby lessons? I figured as much, so I whipped up a little somethin' somethin'. Check it.
Let's say you have an array of numbers and you want the sum of all the squares to be returned. How would you structure a method?
You might be tempted to do something like this:
def squareSum(array) sum = 0 array.each {|num| sum += num**2 } return sum end squareSum([1, 2, 2]) # => 9
That's a perfectly acceptable solution. But you see how we had to initialize the variable 'sum' and then return it at the end? That's no bueno. It's a clear sign that there's a better collection method than each in this case. Each is typically fine to use when you don't want to return anything, but when you do, it tends to be less efficient.
That's where reduce comes in. Reduce takes an array and reduces it to a single value. How exactly? It iterates through the array and keeps / modifies a running total along the way. The total can be in the form of a value, a string, a collection, or really anything depending on the object it's given. In our example, it would look like this:
def squareSum(array) array.reduce(0) {|sum, num| sum + num**2 } end squareSum([1, 2, 2]) # => 9
So here, the initial value is set to 0 (if no value is given, this would be the default anyway). Then the method takes two parameters, a total which we call 'sum' and the current element of the array, which we call 'num'. The sum persists through the loop, so the values at the end of each loop would look like this:
squareSum([1, 2, 2]) Loop Num Sum 1 1 1 2 2 5 3 2 9 # Sum is returned at the end of the last loop
Also FYI, the reduce method is also called inject sometimes and fold sometimes (in other languages). WTF? Those all sound like very different methods, yet they do the exact same thing. Reduce makes the most sense to me semantically, so that's what I'm sticking with.聽
Carry on, my little Rubyist...
5 notes View notes
nishacodes 10 years
Text
Thank you, Flatiron School
It's been one week since the Flatiron School fellowship ended. The last few weeks of class were such a whirlwind that I hardly got a chance to blog. We had a science fair, wrapped up our externship projects, and I prepared a talk for our final meetup. It was crazy, and amazing, and emotional.
The feeling of finishing the programing is incredible, but bittersweet. I still remember those nerve-wrecking interviews with Adam and Ashley back in September. And the moment when I started jumping up and down in the middle of the airport when I found out I had been accepted.
The first day of orientation, I met a bunch of my classmates and had no idea how amazing they were yet. Then day by day, I soon discovered all of the amazing talents each one of them had.
And day by day, we absorbed a little bit more knowledge than we had the day before. Ruby. 聽Sinatra. 聽SQL. 聽JavaScript. 聽D3. 聽AngularJS. 聽SASS. HAML. 聽RSpec. 聽Jasmine. 聽Rails. 聽jQuery. 聽The list goes on.聽
For six months, we coded day in and day out with two incredible teachers, Ashley and Blake. It was intense...but collaborative, not competitive. Everyone learns at different speeds, and everyone has different strengths. We all helped each other fill in the gaps. No one gets left behind.聽
We danced and played, laughed and cried, and I'd do it all over again if I could. Thank you to my teachers and classmates for a truly memorable journey. And thank you to my husband and family for continually supporting me the entire way. It's been an honor.
6 notes View notes
nishacodes 10 years
Text
Heroku does not serve Rails 4 assets by default
I tried to push a Rails 4 app to Heroku today, and come to find out that my assets weren't being served. There are two ways to fix this:
Set聽config.serve_static_assets = true in production.rb
Install the gem 'rails_serve_static_assets' in production
Either one will get you up and running!
0 notes
nishacodes 10 years
Link
I started this blog to bring the concept of open source to business ideas. You can think of this as analogous to GitHub for code. The concept is simple, but its success depends on you.
I鈥檓 going to start by blogging about my ideas (mostly what I consider big ideas in some way). I will try to...
6 notes View notes
nishacodes 10 years
Link
I thought I would compile a list of design & development resources that I have used before and during this program. A lot of this won鈥檛 be new to some of you, regardless they can be helpful as you look for pull together a quick prototype or a final project. Sidebar IO Awwwards.com The...
13 notes View notes
nishacodes 10 years
Link
D3 + Pinterest. Genius.
1 note View note
nishacodes 10 years
Text
Resources for Streamlining your JavaScript Workflow
Yesterday we had a guest speaker, Brittany Storoz, visit us at Flatiron. She's an interactive developer at the New York Times and spoke to us about techniques in streamlining your JavaScript workflow.聽
She recommended incorporating all these resources into the workflow to ensure your codebase stays clean:
JS Beautifier聽- cleans up your indentation and spacing, making your code completely uniform and beautiful
JS Hint or JS Lint聽- both of these error check your JS code for typos or potential problems, but JS Lint is more strict than JS Hint
Testing with Mocha聽- it's a testing framework similar to Jasmine, but it looks way more sleek and minimal, which I appreciate
While incorporating all these steps into your workflow might be a little cumbersome, the great thing is there's a handy tool that AUTOMATES all of these --聽Grunt.
Tumblr media
Grunt is a task runner for many common JavaScript tasks like the ones I mentioned above. So really you should use the above resources for quick usage, but Grunt would be the way to go to incorporate it these tasks into your workflow more efficiently.
1 note View note
nishacodes 10 years
Text
Transitions in D3!
So this was made with D3 today!!! I'm so excited by letters right now.
We learned transitions in class today, which aren't as complex as you'd think because D3 does a lot of the heavy lifting behind the scenes. Have a look at the code in the JS tab.
The main points to know about transitions are:
You need keyed data joins in order to do transitions. This basically remembers which nodes have not changed instead of remapping them each time. Since nodes can persist over time with a keyed data join, you can show transitions
Transitions in D3 are key frame animations with 2 frames: start and end
The end frame is always specified by you
The start frame can be explicitly defined, and if not, will be the current state of the DOM by default
Tween聽infers a type for the start/end pair and produces an animation (i.e. color, number, etc.). This is where a lot of D3 magic happens for us so
Easing聽allows you to specify the duration of the tween (i.e. how much time the transition should occur over)
Check out the code for dets, and ask me questions if you want!
2 notes View notes
nishacodes 10 years
Text
D3's Enter / Update / Exit Lifecycle is like Git
Let's say you have a set of numbers and you want to visualize those numbers as different sized circles, where each circle represents 1 number in your dataset, and the size of each circle directly corresponds to the value of that number.
D3 would be a fine solution to visualizing that data, especially if those numbers might change over time, and some might be removed while others were added. Rather than having to go into your code and manually update the values and circles, D3 would happily do that for you automatically.
This leads me to the enter / update / exit lifecycle of D3, which is a system of keeping the visualization up to date when data is added or removed from the dataset.聽
The way this lifecycle works reminds me a lot of how tracking changes in git works. Think of changes in your local repo being akin to changes in the D3 dataset. And using git to add / commit / remove these changes in order to keep the repo up to date, being similar to the D3 life cycle. Take a look at these diagrams:
D3
Tumblr media
GIT
Tumblr media
The聽enter聽state in D3 represents data that does not currently have a corresponding node, meaning the visualization is not update with that data. In order to add matching nodes, we use the enter and append methods.
bar.enter().append("g"); // where bar is the selection and g represents a node
This is like having changes in your local directory and then adding / committing them to git.聽
The聽update state represents all the data elements that have corresponding nodes. After calling enter and append, all of the data elements have nodes. Similarly, once changes have been committed to git, the repo is up to date with all of those changes.
Finally, the exit state represents data that not longer exists in the dataset, for which nodes need to be removed. You would remove these extraneous nodes by calling the exit and remove methods on the selection.
bar.exit().remove();
You could imagine a similar situation in git when you delete files on your local repo and need to tell git to remove them in the repo as well. If you don't deliberately remove them, they would remain in your repo, just as extra nodes would remain in a D3 visualization if not removed.
These three states represent the different phases that data and elements exist within at any point in time while data is changing. The idea is to cycle through calling these enter and exit methods such that the visualization is dynamically being updated.
8 notes View notes
nishacodes 10 years
Text
Getting the Hang of D3
So聽D3聽is an incredible JavaScript library that visualizes data in a dynamic way. 聽The visualizations can get very complex, like this one below and聽these other examples聽on the D3 website.
Tumblr media
I've started learning the basics of how to turn data into something like this, and while I'm still a ways away from rendering something as complex as the network effect above, it definitely seems feasible. D3 is a lot like jQuery in terms of the syntax and structure of the library, so nothing about how to use it is terribly complex.聽
Today I worked on something simple: creating a simple bar chart in D3. It looked like this:聽
Tumblr media
Okay, I know it's not super exciting. BUT, what's cool is:
The size of all the bars were calculated using D3, so if the dataset changes, the bar chart will change accordingly.聽
The colors were also generated with D3 and vary with the data -- the larger the number, the lighter the color.
Rather than dive into the code step by step, I'll point you to my聽Github repo, which has extensive comments in the code. Also check out this聽tutorial, which is better if you're looking for explanation.聽
Instead, I'd like to talk about how D3 works on a high level. I mentioned that it's similar to jQuery in some ways. In聽my last post, I talked about how to bind聽events聽with selections using the .on() method. Similarly, D3 binds聽data聽with selections using a .data() method. It will follow a pattern like this:
var vizUpdate = ("selection").data(data);
where...
"selection" can be a set of HTML or SVG elements
.data() is a D3 method that binds the selection to the data, and
data is a variable that represents a dataset in the form of an array
The variable vizUpdate is an object that represents the mapping of data to the corresponding nodes. 聽Where there is a mismatch of data to nodes, i.e. when there is more data than nodes or vice versa, other D3 methods take care of updating the mapping accordingly. I'll get into that in more detail in my next post.
2 notes View notes
nishacodes 10 years
Text
Using the .on() method in jQuery
The .on() method in jQuery is used to bind event handler functions with a selector or selectors, like so:
$('#selector').on('click', function() { // stuff that executes when the event occurs });
The same outcome can also be achieved by writing the statement like this:
$('#selector').click(function(){ // stuff that executes when the event occurs });
It might seem like the second method is preferable, as it looks more efficient and dry. However, using the .on() function instead is actually much more versatile for a couple of reasons.
It lets you pass additional data to the handler.
For a given selection, it allows you to bind multiple events.聽
PASSING DATA TO THE EVENT
You may want to pass data to an event handler function so that the action can vary in different circumstances. You can do this by specifying an extra argument in the 'on' method. When you pass data like this, it is stored in the event object, which is passed as an argument to the event handler function. For example:
var myData = { message: 'You clicked on a button' }; $('button').on('click', myData, function(event) { alert(event.data.message); // 'You clicked on a button' will be displayed. });
In this example, myData is the variable that holds the data I want to pass. I pass it in as the second argument of the on method. This data will be stored in the event object (which exists for every event, but is not always explicitly stated). In order for me to access my data in the function, I'll need to pass the event object to the function (written above as 'event').聽
Then, I can access data from the event object with the data property.聽
Calling event.data will return the entire myData object, and called event.data.message will return the value for that property, which in this case is 'You clicked on a button'.
BINDING MULTIPLE EVENTS TO A SINGLE SELECTOR
Another cool thing you can do with the on method, that you can't with specific event functions is specify multiple events for a single selector. Let's say you want different things to happen when you mouseover a selector versus when you click on it.聽
To do this, you would write it in a slightly different format, like so:
$('button').on({ 'click' : function(){ // do something interesting }, // end click function 'mouseover' : function() { // do something else } // end mouseover function });
Here, the events are wrapped in an object literal and separated by commas. For each event handler, the name of the event is the property and the function is the value.聽
1 note View note
nishacodes 10 years
Photo
Tumblr media
399 notes View notes
nishacodes 10 years
Text
JavaScript vs. Ruby: Object-Oriented Programming (Part 1)
Still learning JavaScript, one script at a time. This evening I was reading about object-oriented programming in JavaScript. At first, I found it terribly confusing...but then I started to see the parallels in Ruby. I'm no expert, but here's my take on how it compares to the behavior of classes and objects in Ruby. Why can't it be more like Ruby? *sadface*
JAVASCRIPT
DEFINING A CLASS.聽 JavaScript uses functions as classes.
function Person(){}
INSTANTIATING NEW OBJECTS. You could also use the Object.create method.
var person1 = new Person(); var person2 = new Person();
THE CONSTRUCTOR METHOD.聽 It's called at the moment of instantiation, and there's no need to explicitly define it (analogous to initialize).
function Person(){ alert('A new person!'); } var person1 = new Person(); var person2 = new Person();
PROPERTIES.聽 These are variables available to instances of the class. 'This' refers to the current object, which is very similar to the concept of 'self' in Ruby.
function Person(gender){ this.gender = gender; alert('A new person!'); } var person1 = new Person('male'); var person2 = new Person('female');
聽 METHODS.聽 Methods follow the same logic as properties, except they are functions, and they are defined as functions. To define a method, assign a function to a named property of the class's聽prototype聽property.
function Person(gender){ this.gender = gender; alert('A new person!'); } Person.prototype.sayHello = function() { alert('hello'); }; var person1 = new Person('male'); var person2 = new Person('female'); person1.sayHello(); // hello
RUBY
DEFINING A CLASS.聽聽
class Person end
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 INSTANTIATING NEW OBJECTS.聽
@person1 = Person.new @person2 = Person.new
THE INITIALIZE METHOD.聽 It's automatically called at the moment of instantiation.
class Person def initialize puts "A new person!" end end @person1 = Person.new @person2 = Person.new
聽 INSTANCE VARIABLES.聽These are variables available to instances of the class.聽
class Person def initialize(gender) @gender = gender puts "A new person!" end end @person1 = Person.new('male') @person2 = Person.new('female')
METHODS.聽 Methods are called the same way that instance variables are called on an object. However, they are define within the class using keywords def / end.
class Person def initialize(gender) @gender = gender puts "A new person!" end def say_hello puts "hello" end end @person1 = Person.new('male') @person2 = Person.new('female') @person1.say_hello # hello
2 notes View notes
nishacodes 10 years
Link
Normally, you would run JavaScript in the browser's console, but node.js lets you run it on your server. Great news for Ruby devs!聽What you'll get is a JavaScript console that runs in the terminal which behaves very similarly to irb for Ruby.
There are two ways to install it:
From the terminal
Download the precompiled version聽(easier / or if the former isn't working)
Then you just run $ node to open it up.聽
0 notes
nishacodes 10 years
Text
JavaScript vs. Ruby: The Basics
It's here, it's here, it's finally here!! The day we finally learn JavaScript at the Flatiron School. I'm super excited for JS, mostly because you can do lots of cool visual / interactive things with it, and that makes me happy.
We've been learning Ruby for the past 2 months, so what will be interesting is understanding the similarities and differences between both languages, and not mixing up the syntax.
I did a bit of reading this evening to familiarize myself with the JavaScript basics. On a high level, it's incredibly similar to Ruby.
Like Ruby, Javascript:
is an object-oriented language
has similar value types (number, string, boolean, object, function)
stores data in variables, which can have local or global scope
evaluates functions (which are methods in Ruby)
has similar loops, conditionals and operators
Variables, values and functions are the building blocks of the language. Conceptually, it's not difficult to understand being similar to Ruby. However, there are a number of subtle syntactic differences that are worth pointing out.
JAVASCRIPT
Defining a variable:
var myNumber = 2;
Converting a string to a number:
Number("2"); // => 2
While and For loops:
// WHILE LOOP var n=1; while (n <= 10) { print(n); n++; } // notice the use of semicolons, parenthesis and brackets // also notice the ++ function, which adds 1 to n
// FOR LOOP for(var n=1; n <=10; n++){ if (n < 5) print(n); else if (n == 5) print("FIVE"); else print(String(n)); } // 1 2 3 4 FIVE "6" "7" "8" "9" "10" // 3 arguments are given: 1) the state of variable to evaluate, 2) the condition, 3) the iterator
Blocks:
for (var i = 1; i < 101; i++) { console.log(i*5); } // The block is defined inside the curly braces
The function 'typeof':
typeof(5) // => number typeof("hello") // => string typeof(true) // => boolean
RUBY
Defining a variable:
myNumber = 2
Converting a string to a number:
"2".to_i # => 2
While and For loops:
# WHILE LOOP n=1 while n <=10 puts n n+=1 end
# FOR LOOP for n in 1..10 if n < 5 puts n elsif n == 5 puts "FIVE" else puts n.to_s end end # 1 2 3 4 FIVE "6" "7" "8" "9" "10"
Blocks:
100.times do |i| puts (i + 1)*5 end # The block is defined between 'do' and 'end'
100.times { |i| puts (i + 1)*5 } # The block is defined between the curly braces
The method 'class':
5.class # => Fixnum "hello".class # => String true.class # => TrueClass # The block is defined between the curly braces
NOTE: In case you are wondering how I created the two-column layout, it's just a bit of custom CSS ;-).聽 Both columns have class .column { width: 50%; a bit of padding; float: left; display: inline-block;}
2 notes View notes
nishacodes 10 years
Text
Join Tables: Here's the deal
Here's the thing about join tables in Rails. They are handy, but they are tricky, not to mention extremely picky. I don't want you to have waste any time debugging join tables, so I shall impart my newfound knowledge on you here. You're welcome.
When do you need join tables?
It's simple. Join tables bridge the relationship between two resources that both have many of the other. If one resource has_many and the other belongs_to, you don't need a join table, because it can be mapped out in two tables no problem. When they both has_many of each other, you need a third table because it creates a third dimension.
How does the migration look?
Let's say we have two tables, Companies and People. Companies have many people, and People have many companies (speaking in the context that people work at many different companies over time). You might first run the command to create the migration:
$ rails g migration CreateTableCompanyPeople
class CreateTableCompanyPeople < ActiveRecord::Migration def change create_table :company_people, :id => false do |t| t.integer :company_id t.integer :person_id end end end
The details are VERY important here. This file wouldn't pre-populate unless you specify the column names, but that's no matter, you can just write it in yourself. Note these things:
The first table name is written in singular and the second in plural; they are joined by an underscore to be the name of the jointable 聽It聽must be written like that and only that (I'll tell you why in a minute.) No funny business like :companies_people is allowed
The name of the file should also be written accordingly
The column names, or IDs, will always be singular
Rails understands how to pluralize most words, including person to people
It says 'create_table', not 'create_join_table' (some sources suggest the ladder, but it can be buggy)
You'd be surprised how many different versions of creating a join table are out there. I've tried them all, including the way described in the Ruby Docs, which btw聽doesn't work, at least not in Rails 3.2.聽
What about models?
You need them! Specifically, you need 3 models in this example. Company, Person, and CompanyPerson (all singular). The name of your model has a direct relationship with the name of your tables. Rails has a system:
For every model name, it will pluralize it to get the table name
If there are two words in the model name (identified by CamelCase), it will only pluralize the second word and will add an underscore between the two words
That's why it's so important to write your migrations perfectly. If we called our table companies_people and our model CompanyPerson, we would get an error when trying to call any Active Record methods, because our model would be looking for the company_people table, which doesn't exist.
The other important piece you need in the models are the correct associations, like so:
class Company < ActiveRecord::Base has_many :people, :through => :company_people has_many :company_people end
class Person < ActiveRecord::Base has_many :companies, :through => :company_people has_many :company_people end
class CompanyPerson < ActiveRecord::Base belongs_to :company belongs_to :person end
It's a little strange. A company has_many company_people? What's that all about? But when you see whats happening in the tables, it actually does make sense:
Tumblr media
Here, you see in the Company_People table that there are two records with company_id of 1. If each record in that table is a "company_person", then company 1 has many company_people. See?
Company 1 also has many people through the join table Company_People, so that association makes sense too.
The Best Way to do it
Given the particulars of how these bad boys operate, I would recommend doing it the same way every time. The most full-proof way I know is to generate the model for the join, which in turn will create a migration for you.
$ rails g model CompanyPerson company_id:integer person_id:integer
This would give you:
A model with class CompanyPerson and
A migration file that has everything filled out for you already to create table company_people
It doesn't get much better than that (with joins at least).聽
3 notes View notes