Iacutone.rb

coding and things

Refactoring Client Side Validations

| Comments

I have been working on refactoring my client side JavaScript validations on an application. My tech lead gave me some illuminating tips on how to refactor my non-DRY code. Here is an example of the pre-refactored code.

_form.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<%= form_for(@order) do |f| %>
  <div class='your_info'>
    <h3>2. Your Information</h3>
    <div class="clearfix">
      <%= f.label :first_name, 'First name*' %>
      <div class="input">
        <%= f.text_field :first_name %>
        <span id="first_name_error"></span>
      </div>
      <div class="input">
        <%#= f.hidden_field :customer_id, value: current_user.id unless current_user.id == nil %>
      </div>
    </div>
    <div class="clearfix">
      <%= f.label :last_name, 'Last name*' %>
      <div class="input">
        <%= f.text_field :last_name %>
        <span id="last_name_error"></span>
      </div>
    </div>
    <div class="clearfix">
      <%= f.label :email, 'Email*' %>
      <div class="input">
        <%= f.text_field :email %>
        <span id="email_error"></span>
      </div>
    </div>
  </div>
  <%= f.submit "Submit your Order", class: 'btn btn-primary btn-lg', id: 'button', data: { confirm: "Place order?" } %>
<% end %>

So, let's start with this basic form and sprinkle it with some JQuery and Javascript for client side validations.

users.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Initial State for Form
$('.your_info').hide();

// validations
var first_name = $('input#order_first_name');
var last_name = $('input#order_last_name');
var email = $('input#order_email');

// event listeners
first_name.keyup(function(){
  validateFirstName();
});

last_name.keyup(function(){
  validateLastName();
});

email.keyup(function(){
  validateEmail();
});

function validateFirstName(){
  var first_name_val = first_name.val();
  if(first_name_val.length == 0) {
    first_name_error.show().text("First name needed.").addClass('error_class');
    return false;
  }
  else {
    first_name_error.hide();
    return true;
  }
}

function validateLastName(){
  var last_name_val = last_name.val();
  if(last_name_val.length == 0) {
    last_name_error.show().text("Last name needed.").addClass('error_class');
    return false;
  }
  else {
    last_name_error.hide();
    return true;
  }
}

function validateEmail(){
  var email_val = email.val();
  if(email_val.length == 0) {
    email_error.show().text("Email needed.").addClass('error_class');
    return false;
  }
  else {
    email_error.hide();
    return true;
  }
}

Clearly, this is not DRY and will easily get out of comtrol. However, using HTML data attributes solves this problem. Here is a good summary about data attributes by John Resig.

_form.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%= form_for(@order) do |f| %>
  <div class='your_info'>
    <h3>2. Your Information</h3>
    <div class="clearfix">
      <%= f.label :first_name, 'First name*' %>
      <div class="input">
        <%= f.text_field :first_name, :data => {:error => 'First name'} %>
        <span id="first_name_error"></span>
      </div>
    </div>
    <div class="clearfix">
      <%= f.label :last_name, 'Last name*' %>
      <div class="input">
        <%= f.text_field :last_name, :data => {:error => 'Last name'} %>
        <span id="last_name_error"></span>
      </div>
    </div>
    <div class="clearfix">
      <%= f.label :email, 'Email*' %>
      <div class="input">
        <%= f.text_field :email, :data => {:error => 'Email'} %>
        <span id="email_error"></span>
      </div>
    </div>
  <%= f.submit "Submit your Order", class: 'btn btn-primary btn-lg', id: 'button', data: { confirm: "Place order?" } %>
<% end %>
users.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$('input').keyup(function(){
  blankValidation.call(this);
});

function blankValidation(){
  var error_name = $(this).data('error');
  console.log(error_name);
  var value = $(this).val();
  console.log(value);
  if(error_name !== undefined){
    var error_id = ('#' + error_name.toLowerCase().replace(' ', '_') + ('_error'));
    var error_message = $(error_id);
    if(value.length === 0) {
      error_message.show().text(error_name + " needed.").addClass('error_class');
      return false;
    }
    else {
      error_message.hide();
      return true;
    }
  }
}

We can dynamically call the data attribute for each element. For example, the error_name value the keyup event(m) will console.log (=> First name, m). The call method allows us to refactor all of our keyup event listeners into one method. The call method as defined by the Mozilla guide "calls a function with a given this value and arguments provided individually."

h/t Dan Porter

Reference

Testing Your Way to Success

| Comments

I have been immersed in production codebases for my Fohr Card and Fractured Atlas projects. At first, it feel initimidating trying to figure out all of the models and related associations. I have found that a great way to wrap your head around the code base is to create a new branch and test the code.

A good basic set-up is to start unit testing the models. In order to do this depends on if your codebase is using a relational database or something like Mongoid.

Relational Databases

Gemfile
1
2
3
4
5
6
7
8
9
10
11
 group :development do
    gem 'guard-rspec', require: false
  end

  group :test do
     gem 'rspec-rails'
     gem 'factory_girl_rails'
     gem 'faker'
     gem 'shoulda-matchers'
     gem 'terminal-notifier-guard'
  end
  • Guard RSpec waits for you to save your files and automatically runs your tests, thereby reducing the time needed to run tests.
  • I like the RSpec syntax over Unit Test and Mini Test.
  • Factory Girl Rails creates objects for your tests. This gem deserves its own blog post.
  • The Faker Gem is used in conjunction with Factory Girl Rails to create fake data.
  • I like to use Shoulda Matchers to test validaitons and associations in the code. This gem and firing up Rails Console to play with the objects in my testing is the crux to learning a new codebase.
  • Some people find Terminal Notifier annoying, but it helps me know if my tests pass when I have Sublime maximized on my 11 inch MacBook Air screen.

Mongoid

Gemfile
1
2
3
4
5
6
7
8
9
10
11
 group :development do
    gem 'guard-rspec', require: false
  end

  group :test do
    gem 'fabrication'
    gem 'faker'
    gem 'rspec-rails'
    gem 'mongoid-rspec'
    gem 'terminal-notifier-guard'
  end

The gems for Mongoid testing are similar to those used in testing with a relational database.

  • The Fabrication gem is similar to building objects with Factory Girl, except the documentation website rocks.
  • The Mongoid RSpec gem is similar to Shoulda-Matchers

Gems

Guard RSpec
RSpec Rails
Factory Girl Rails
Faker
Shoulda Matchers
Terminal Notifier Guard
Fabrication
Mongoid RSpec

Other Resources

I found this book invaluable in learning best practices in testing: Everday RSpec
h/t Victoria Friedman

Changing Your Password From Scratch

| Comments

So say you are using devise and have none of the has_secure_password medthod available to you. One should learn the bcrypt gem... and needs to abstract some methods in order to parse an encrypted password. Cool, Bcrypt can do that, as located here. Here is my modified code in order to confirm if a new password in order to apply a boolean value to an inputed password.

edit.html.haml lang: ruby
1
2
3
4
5
6
7
8
9
10
11
 %li
      = f.label :current_password
      = f.password_field :current_password
      # => 'password'
    %li
      = f.label :new_password, 'New Password'
      = f.password_field :new_password
      # => 'new_password'

  .buttons
    %button Save
user.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

  def authenticate(unencrypted_password)
    if BCrypt::Password.new(encrypted_password) == unencrypted_password && self
      bcrypt = ::BCrypt::Password.new(encrypted_password)
      # creates a bcrypt variable if the encrypted passwors result is true
      # => "$2a$10$wgOzLhy84peHUD9wr9UkgOKRpwfls/0h48NYVvKIOdUdbz3XOEpSK" 
      password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt)
      # then salts the new password
      # => "$2a$10$VUNoD3xdAp7ytTIsTyH5feY.DNUKA4efIdkcI6ViBQ532o8lyNV/e" 
      user = nil unless reset_secure_compare(password, encrypted_password)
      return true
    else BCrypt::Password.new(encrypted_password) != unencrypted_password && self
      return false
    end
  end

You might be wondering what the reset_secure_password method is doing. Well, it is pulled from the Devise docs and is preventing timing attacks, when an attacker attempts to compromise an encryption by analyzing the time taken in order to execute the password and salting algorithms.

Cool, now I can pass my current_password attribute to make sure it is true. I need to make a custom Active Record Validations.

user.rb
1
2
3
4
5
 def correct_password_update_validator
    if self.authenticate(current_password) == true and current_password.present? and new_password.present?
      self.encrypted_password = ::BCrypt::Password.create(new_password)
    end
   end

If this validates, encrypted_password on the database returns true. Now I need validations for events with blank fields (I want nothing to happen), and also, if current_password is blank and new_password and present, visa versa.

user.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 validate :incorrect_password_update_validator, on: :update
  validate :correct_password_update_validator, on: :update
  validate :current_password_present, on: :update
  validate :new_password_present, on: :update
  validate :current_password_true_present, on: :update

  private

  def current_password_true_present
    if self.authenticate(current_password) == true and new_password.blank? and current_password.present?
      errors.add(:new_password, " needs to be filled out.")
    end
  end

  def current_password_present
    if self.authenticate(current_password) == false and new_password.present? and current_password.blank?
      errors.add(:current_password, " needs to be filled out.")
    end
  end

  def new_password_present
    if self.authenticate(current_password) == false and new_password.blank? and current_password.present?
      errors.add(:new_password, " needs to be filled out.")
    end
  end

  def incorrect_password_update_validator
    if self.authenticate(current_password) == false and current_password.present? and new_password.present?
      errors.add(:current_password, " does not match.")
    end
  end

  def reset_secure_compare(a, b)
    return false if a.blank? || b.blank? || a.bytesize != b.bytesize
    l = a.unpack "C#{a.bytesize}"

    res = 0
    b.each_byte { |byte| res |= byte ^ l.shift }
    res == 0
  end

Now, all use cases of the user improperly editing the form result in false and a validation error occurs.

Grep and Scan Methods With Regular Expressions in Ruby

| Comments

I am creating an app to provide food cart locations in Manhattan. Here is the code. Food carts generally post their locations on Twitter; in order to create latitude and longitude coordinates, I needed to parse tweets. This is where scan and grep play their role, to match elements in a tweet string. Let's say this is our tweet: "53rd and park. Ready by 11!" This string is database column in my locations model.

Code for scan method.

1
2
3
4
5
 tweet = "53rd and park. Ready by 11!"
  tweet.scan(/53/)
  # => ["53"] 
  tweet.scan(/Park/i)
  # => ["park"]

The scan method takes a string as an input. Also, the i is used in the regular expression in order to make it case insensitive.

1
2
 tweet.scan(/Park/)
  #  => [] 

Code for grep method.

1
2
3
4
5
6
7
 tweet = "53rd and park. Ready by 11!"
  tweet_array = tweet.split
  # => ["53rd", "and", "park.", "Ready", "by", "11!"] 
  tweet_array.grep(/53/)
  # => ["53rd"]
  tweet_array.grep(/Park/i)
  # => ["park."]

The grep method takes an array as an input, so use the string split method to turn it into an array seperated by commas. Also, the regular expression matches the entire string. The grep method seems to be more suited as an alternative for the select and map methods. This blog post goes into further detail explaining more cases to use the grep method over more familiar methods.

Hiding Multiple Checkboxes With JQuery

| Comments

I have been developing a quiz app for practice with a more complex schema interface. I wanted to dive deeper into CoffeScript and found the opportunity while trying to figure out how a student can add an answer to a given quiz. If a checkbox for a given answer is checked, I wanted the remaining checkboxes to disappear. Also, if the student checked the incorrect box, the browser should render all checkboxes again. Here is my code.

questions.js.coffee
1
2
3
4
5
6
7
8
9
   $('form').on 'click', '.checker', (event) ->
      boxes = $(":checkbox:checked")
      nboxes = $(":checkbox:not(:checked)")
      if boxes.length == 1
          $('.checker_label').hide()
          nboxes.hide()
      if boxes.length == 0
          $('.checker_label').show()
          nboxes.show()

... and the view

_form.html.haml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Quiz:
= @quiz.name

= form_for @question do |f|
  = f.hidden_field :quiz_id, value: @quiz.id
  = f.label "What is your question?"
  = f.text_field :content
  %br
  %fieldset
      = f.fields_for :answers do |builder|
          = builder.label :content, "Answer"
          = builder.text_field :content
          = builder.label "Correct answer?", class:'checker_label'
          = builder.check_box :is_correct, class: 'checker'
      %br
  = link_to_add_fields "Add an answer choice", f, :answers
  %br
  = f.submit

Sidekiq and Carrierwave, Part 3

| Comments

I decided to use the Carrierwave Backgrounder Gem in order to asynchronously upload photos to Amazon S3. This is a different gem than the one Ryan Bates uses in his Railscast. I was having difficulty implimenting the Carrierwave Direct Gem However, the Backgrounder Gem works great! This is the last installment of the three part series on uploading photos.

This is the final version of the avatar_uploader.rb file. Just add line 3, which is in the Backgrounder documentaion.

avatar_uploader.rb lang: ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  class AvatarUploader < CarrierWave::Uploader::Base
  # include CarrierWaveDirect::Uploader
  include ::CarrierWave::Backgrounder::Delay

  # Include RMagick or MiniMagick support:
  include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
  include Sprockets::Helpers::RailsHelper
  include Sprockets::Helpers::IsolatedHelper

  # Choose what kind of storage to use for this uploader:
  # storage :file
  storage :fog

  include CarrierWave::MimeTypes
  process :set_content_type

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  # def store_dir
  #   "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  # end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  version :thumb do
    process :resize_to_limit => [150, 150]
  end

  version :profile do
    process :resize_to_limit => [200, 200]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  # def extension_white_list
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end
  end

Also, add this code to your model.

profile.rb
1
2
 mount_uploader :avatar, AvatarUploader
  process_in_background :avatar

Following the install instructions, this file is created in the initializers directory.

initializers/carrierwave_backgrounder.rb
1
2
3
4
5
6
7
8
 CarrierWave::Backgrounder.configure do |c|
    # c.backend :delayed_job, queue: :carrierwave
    # c.backend :resque, queue: :carrierwave
    c.backend :sidekiq, queue: :carrierwave
    # c.backend :girl_friday, queue: :carrierwave
    # c.backend :qu, queue: :carrierwave
    # c.backend :qc
  end

Then boot up Sidekiq to listen for jobs with sidekiq -q carrierwave command in your terminal. You might need to start your Redis server with the command redis-server. Your background worker should now asynchronously process background jobs!

Sidekiq also has a cool interface to show what workers are up, how many successes and failures there have been and some other neat features. It is real easy to set up. First add the following code to your Gemfile.

Gemfile
1
2
 gem 'slim', '>= 1.1.0'
  gem 'sinatra', '>= 1.3.0', :require => nil

Then create this route with the require line before the beginning of the block.

routes.rb
1
2
3
4
 require 'sidekiq/web'

  mount Sidekiq::Web => '/sidekiq'

I really like this gem and recommend it to anyone trying to run background processes to upload pictures via Carrierwave.

h/t Blake Johnson

Gon Gem

| Comments

I ran into difficulties trying to find a way to implement jQuery in a modal. It is not possible to use remote: true in a form_tag with Twitter Bootstrap. I successfully used the Gon Gem in order to remove elements from the DOM when an instance variable reached a certain number. If you find yourself in the position of needing to remove elements from a modal, this gem seems to be the way to go.

user_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37


    def create
      @user = User.new(params[:user])

      if @user.save

        @day_one_counter = []
        @day_one_counter = User.pluck(:time1)

        #@day_one_counter outputs an array of elements from the :time1 column. => ["11:00", "11:00", nil, nil, nil]

        b = Hash.new(0)

        @day_one_counter.each do |v|
          b[v] += 1
        end

        #the block increments the key/value pairs in the instantiated Hash. => {"11:00"=>2, nil=>3}

        @time1 = b["11:00"]
        gon.time1 = @time1

        #@time1 pulls out the value of the pair => 2
        #gon.time1 => 2, in order to use the @time1 instance variable in users.js

        @time2 = b["11:20"]
        gon.time2 = @time2

        @time3 = b["11:40"]
        gon.time3 = @time3

        render :time
      else
        render :new
      end
    end

This is a conintuation of the Pluck Method from my last blog post. For an overview of what is happening, read the comments provided above. With the gone.time1 variable, I can now use jQuery in my users.js file in order to remove elements from the DOM that go over a given number, in this case 5.

users.js
1
2
3
4
5
6
7
   if (gon.time1 > 4) {
      $('.wrapper1').remove();
  }

  if (gon.time2 > 4) {
      $('.wrapper2').remove();
  }

...and the form

_time1.html.erb
1
2
3
4
5
6
7
 <%= form_for @user do |f| %>
     <div class='wrapper1' id='pad'>11:00 A.M. <%= f.radio_button(:time1, '11:00') %><br /><%= 5 - @time1 unless @time1 == nil %> spots remaining.</div>
      <div class='wrapper2' id='pad'>11:20 A.M. <%= f.radio_button(:time1, '11:20') %><br /><%= 5 - @time2 unless @time2 == nil %> spots remaining.</div>
      <div class='wrapper'><%= f.radio_button(:time1, 'No time.') %>  Interested but not available during these times. Please inform me of future conversation opportunities.<br /></div>
 <%= f.hidden_field :day, :value => 'July 10' %>
 <button class="btn btn-inverse" type="submit"class="actions">Submit</button>
 <% end %>

Since the @time1 instance variable and therefore, gon.time1 are saved after my create action, the applicable time is > 4 if I want a total of 5 elements for a particular time on my :time1 column. The next time the modal is visited, the element will be removed!

I am so excited I found this gem and got my modal to work correctly! Also, a thanks for Railscast for the tutorial on the gem.

Passing Data to Javascript

Pluck Method in Active Record

| Comments

The past few days, I have been building a database to store some information for my friend Shari, a Peace Corps recruiter. The database includes, a name, email and phone number. Things got tricky building a date/time models and validations. Every given time has six time slots for a user to sign up. My conclusion to this problem was to create a different database column for every given time slot. Then, I used the pluck method on my Active Record database in order to turn all of my time columns into strings in an array. However, in Rails 3, pluck only excepts one column to turn into an array. This feature is being changed in Rails 4 according to this blog post where he describes how to tamper with the the Active Record library or create a module to provide a pluck_all method for a Rails 3 application. I implemented this code, and was returned an array of hashes which did not help my cause. But this is an interesting concept and it was fun and insightful reading the source code.

users_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  def create
    @user = User.new(params[:user])

    if @user.save

      @day_one_counter = []
      @day_one_counter = User.pluck(:time1)

      @day_two_counter = []
      @day_two_counter = User.pluck(:time2)

      b = Hash.new(0)
      c = Hash.new(0)

      @day_one_counter.each do |v|
        b[v] += 1
      end

      @day_two_counter.each do |v|
        c[v] += 1
      end

      @time1 = b["11:30"]
      @time2 = b["11:45"]
      @time3 = b["12:00"]
      @time4 = b["12:15"]
      @time5 = b["12:30"]
      @time6 = b["12:45"]
      @time7 = b["1:00"]
      @time8 = b["1:15"]
      @time9 = b["1:30"]
      @time10 = b["1:45"]
      @time11 = b["5:00"]
      @time12 = b["5:15"]
      @time13 = b["5:30"]
      @time14 = b["5:45"]
      @time15 = b["6:00"]
      @time16 = b["6:15"]
      @time17 = b["6:30"]
      @time18 = b["6:45"]
      @time19 = b["7:00"]
      @time20 = b["7:15"]

      @time21 = c["11:30"]
      @time22 = c["11:45"]
      @time23 = c["12:00"]
      @time24 = c["12:15"]
      @time25 = c["12:30"]
      @time26 = c["12:45"]
      @time27 = c["1:00"]
      @time28 = c["1:15"]
      @time29 = c["1:30"]
      @time30 = c["1:45"]
      @time31 = c["5:00"]
      @time32 = c["5:15"]
      @time33 = c["5:30"]
      @time34 = c["5:45"]
      @time35 = c["6:00"]
      @time36 = c["6:15"]
      @time37 = c["6:30"]
      @time38 = c["6:45"]
      @time39 = c["7:00"]
      @time40 = c["7:15"]

      # respond_to do |format|
      #   format.html
      #   format.js
      # end   

      render :time
    else
      render :new
    end
  end

This code gets really cumbersome the more time columns I add, so my next step is to DRY this shit up. But hell, it works and is going to make my friend's life easier, yay! for technology.

Using Impress.js With Rails

| Comments

I recently had an interview at an awesome creative agency, Canvas and wanted to show them something unique in order to make me stand out. I decided to build a thank you card with Impress.js. This is the thank you card I sent to their CTO. I enjoyed playing with Impress.js and will definitely incorporate it into many more applications in the future. However, there is not much documentation about how to get Impress to play nicely in a Rails app. The app was breaking in production, but working in development. The code following the impress.js file below specifies where to load the Javascript.

app/assets/javascripts/impress.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
/**
 * impress.js
 *
 * impress.js is a presentation tool based on the power of CSS3 transforms and transitions
 * in modern browsers and inspired by the idea behind prezi.com.
 *
 *
 * Copyright 2011-2012 Bartek Szopka (@bartaz)
 *
 * Released under the MIT and GPL Licenses.
 *
 * ------------------------------------------------
 *  author:  Bartek Szopka
 *  version: 0.5.3
 *  url:     http://bartaz.github.com/impress.js/
 *  source:  http://github.com/bartaz/impress.js/
 */

/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true,
         noarg:true, noempty:true, undef:true, strict:true, browser:true */

// You are one of those who like to know how thing work inside?
// Let me show you the cogs that make impress.js run...
(function ( document, window ) {
    'use strict';

    // HELPER FUNCTIONS

    // `pfx` is a function that takes a standard CSS property name as a parameter
    // and returns it's prefixed version valid for current browser it runs in.
    // The code is heavily inspired by Modernizr http://www.modernizr.com/
    var pfx = (function () {

        var style = document.createElement('dummy').style,
            prefixes = 'Webkit Moz O ms Khtml'.split(' '),
            memory = {};

        return function ( prop ) {
            if ( typeof memory[ prop ] === "undefined" ) {

                var ucProp  = prop.charAt(0).toUpperCase() + prop.substr(1),
                    props   = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' ');

                memory[ prop ] = null;
                for ( var i in props ) {
                    if ( style[ props[i] ] !== undefined ) {
                        memory[ prop ] = props[i];
                        break;
                    }
                }

            }

            return memory[ prop ];
        };

    })();

    // `arraify` takes an array-like object and turns it into real Array
    // to make all the Array.prototype goodness available.
    var arrayify = function ( a ) {
        return [].slice.call( a );
    };

    // `css` function applies the styles given in `props` object to the element
    // given as `el`. It runs all property names through `pfx` function to make
    // sure proper prefixed version of the property is used.
    var css = function ( el, props ) {
        var key, pkey;
        for ( key in props ) {
            if ( props.hasOwnProperty(key) ) {
                pkey = pfx(key);
                if ( pkey !== null ) {
                    el.style[pkey] = props[key];
                }
            }
        }
        return el;
    };

    // `toNumber` takes a value given as `numeric` parameter and tries to turn
    // it into a number. If it is not possible it returns 0 (or other value
    // given as `fallback`).
    var toNumber = function (numeric, fallback) {
        return isNaN(numeric) ? (fallback || 0) : Number(numeric);
    };

    // `byId` returns element with given `id` - you probably have guessed that ;)
    var byId = function ( id ) {
        return document.getElementById(id);
    };

    // `$` returns first element for given CSS `selector` in the `context` of
    // the given element or whole document.
    var $ = function ( selector, context ) {
        context = context || document;
        return context.querySelector(selector);
    };

    // `$$` return an array of elements for given CSS `selector` in the `context` of
    // the given element or whole document.
    var $$ = function ( selector, context ) {
        context = context || document;
        return arrayify( context.querySelectorAll(selector) );
    };

    // `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data
    // and triggers it on element given as `el`.
    var triggerEvent = function (el, eventName, detail) {
        var event = document.createEvent("CustomEvent");
        event.initCustomEvent(eventName, true, true, detail);
        el.dispatchEvent(event);
    };

    // `translate` builds a translate transform string for given data.
    var translate = function ( t ) {
        return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) ";
    };

    // `rotate` builds a rotate transform string for given data.
    // By default the rotations are in X Y Z order that can be reverted by passing `true`
    // as second parameter.
    var rotate = function ( r, revert ) {
        var rX = " rotateX(" + r.x + "deg) ",
            rY = " rotateY(" + r.y + "deg) ",
            rZ = " rotateZ(" + r.z + "deg) ";

        return revert ? rZ+rY+rX : rX+rY+rZ;
    };

    // `scale` builds a scale transform string for given data.
    var scale = function ( s ) {
        return " scale(" + s + ") ";
    };

    // `perspective` builds a perspective transform string for given data.
    var perspective = function ( p ) {
        return " perspective(" + p + "px) ";
    };

    // `getElementFromHash` returns an element located by id from hash part of
    // window location.
    var getElementFromHash = function () {
        // get id from url # by removing `#` or `#/` from the beginning,
        // so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work
        return byId( window.location.hash.replace(/^#\/?/,"") );
    };

    // `computeWindowScale` counts the scale factor between window size and size
    // defined for the presentation in the config.
    var computeWindowScale = function ( config ) {
        var hScale = window.innerHeight / config.height,
            wScale = window.innerWidth / config.width,
            scale = hScale > wScale ? wScale : hScale;

        if (config.maxScale && scale > config.maxScale) {
            scale = config.maxScale;
        }

        if (config.minScale && scale < config.minScale) {
            scale = config.minScale;
        }

        return scale;
    };

    // CHECK SUPPORT
    var body = document.body;

    var ua = navigator.userAgent.toLowerCase();
    var impressSupported =
                          // browser should support CSS 3D transtorms 
                           ( pfx("perspective") !== null ) &&

                          // and `classList` and `dataset` APIs
                           ( body.classList ) &&
                           ( body.dataset ) &&

                          // but some mobile devices need to be blacklisted,
                          // because their CSS 3D support or hardware is not
                          // good enough to run impress.js properly, sorry...
                           ( ua.search(/(iphone)|(ipod)|(android)/) === -1 );

    if (!impressSupported) {
        // we can't be sure that `classList` is supported
        body.className += " impress-not-supported ";
    } else {
        body.classList.remove("impress-not-supported");
        body.classList.add("impress-supported");
    }

    // GLOBALS AND DEFAULTS

    // This is were the root elements of all impress.js instances will be kept.
    // Yes, this means you can have more than one instance on a page, but I'm not
    // sure if it makes any sense in practice ;)
    var roots = {};

    // some default config values.
    var defaults = {
        width: 1024,
        height: 768,
        maxScale: 1,
        minScale: 0,

        perspective: 1000,

        transitionDuration: 1000
    };

    // it's just an empty function ... and a useless comment.
    var empty = function () { return false; };

    // IMPRESS.JS API

    // And that's where interesting things will start to happen.
    // It's the core `impress` function that returns the impress.js API
    // for a presentation based on the element with given id ('impress'
    // by default).
    var impress = window.impress = function ( rootId ) {

        // If impress.js is not supported by the browser return a dummy API
        // it may not be a perfect solution but we return early and avoid
        // running code that may use features not implemented in the browser.
        if (!impressSupported) {
            return {
                init: empty,
                goto: empty,
                prev: empty,
                next: empty
            };
        }

        rootId = rootId || "impress";

        // if given root is already initialized just return the API
        if (roots["impress-root-" + rootId]) {
            return roots["impress-root-" + rootId];
        }

        // data of all presentation steps
        var stepsData = {};

        // element of currently active step
        var activeStep = null;

        // current state (position, rotation and scale) of the presentation
        var currentState = null;

        // array of step elements
        var steps = null;

        // configuration options
        var config = null;

        // scale factor of the browser window
        var windowScale = null;

        // root presentation elements
        var root = byId( rootId );
        var canvas = document.createElement("div");

        var initialized = false;

        // STEP EVENTS
        //
        // There are currently two step events triggered by impress.js
        // `impress:stepenter` is triggered when the step is shown on the 
        // screen (the transition from the previous one is finished) and
        // `impress:stepleave` is triggered when the step is left (the
        // transition to next step just starts).

        // reference to last entered step
        var lastEntered = null;

        // `onStepEnter` is called whenever the step element is entered
        // but the event is triggered only if the step is different than
        // last entered step.
        var onStepEnter = function (step) {
            if (lastEntered !== step) {
                triggerEvent(step, "impress:stepenter");
                lastEntered = step;
            }
        };

        // `onStepLeave` is called whenever the step element is left
        // but the event is triggered only if the step is the same as
        // last entered step.
        var onStepLeave = function (step) {
            if (lastEntered === step) {
                triggerEvent(step, "impress:stepleave");
                lastEntered = null;
            }
        };

        // `initStep` initializes given step element by reading data from its
        // data attributes and setting correct styles.
        var initStep = function ( el, idx ) {
            var data = el.dataset,
                step = {
                    translate: {
                        x: toNumber(data.x),
                        y: toNumber(data.y),
                        z: toNumber(data.z)
                    },
                    rotate: {
                        x: toNumber(data.rotateX),
                        y: toNumber(data.rotateY),
                        z: toNumber(data.rotateZ || data.rotate)
                    },
                    scale: toNumber(data.scale, 1),
                    el: el
                };

            if ( !el.id ) {
                el.id = "step-" + (idx + 1);
            }

            stepsData["impress-" + el.id] = step;

            css(el, {
                position: "absolute",
                transform: "translate(-50%,-50%)" +
                           translate(step.translate) +
                           rotate(step.rotate) +
                           scale(step.scale),
                transformStyle: "preserve-3d"
            });
        };

        // `init` API function that initializes (and runs) the presentation.
        var init = function () {
            if (initialized) { return; }

            // First we set up the viewport for mobile devices.
            // For some reason iPad goes nuts when it is not done properly.
            var meta = $("meta[name='viewport']") || document.createElement("meta");
            meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no";
            if (meta.parentNode !== document.head) {
                meta.name = 'viewport';
                document.head.appendChild(meta);
            }

            // initialize configuration object
            var rootData = root.dataset;
            config = {
                width: toNumber( rootData.width, defaults.width ),
                height: toNumber( rootData.height, defaults.height ),
                maxScale: toNumber( rootData.maxScale, defaults.maxScale ),
                minScale: toNumber( rootData.minScale, defaults.minScale ),
                perspective: toNumber( rootData.perspective, defaults.perspective ),
                transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration )
            };

            windowScale = computeWindowScale( config );

            // wrap steps with "canvas" element
            arrayify( root.childNodes ).forEach(function ( el ) {
                canvas.appendChild( el );
            });
            root.appendChild(canvas);

            // set initial styles
            document.documentElement.style.height = "100%";

            css(body, {
                height: "100%",
                overflow: "hidden"
            });

            var rootStyles = {
                position: "absolute",
                transformOrigin: "top left",
                transition: "all 0s ease-in-out",
                transformStyle: "preserve-3d"
            };

            css(root, rootStyles);
            css(root, {
                top: "50%",
                left: "50%",
                transform: perspective( config.perspective/windowScale ) + scale( windowScale )
            });
            css(canvas, rootStyles);

            body.classList.remove("impress-disabled");
            body.classList.add("impress-enabled");

            // get and init steps
            steps = $$(".step", root);
            steps.forEach( initStep );

            // set a default initial state of the canvas
            currentState = {
                translate: { x: 0, y: 0, z: 0 },
                rotate:    { x: 0, y: 0, z: 0 },
                scale:     1
            };

            initialized = true;

            triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] });
        };

        // `getStep` is a helper function that returns a step element defined by parameter.
        // If a number is given, step with index given by the number is returned, if a string
        // is given step element with such id is returned, if DOM element is given it is returned
        // if it is a correct step element.
        var getStep = function ( step ) {
            if (typeof step === "number") {
                step = step < 0 ? steps[ steps.length + step] : steps[ step ];
            } else if (typeof step === "string") {
                step = byId(step);
            }
            return (step && step.id && stepsData["impress-" + step.id]) ? step : null;
        };

        // used to reset timeout for `impress:stepenter` event
        var stepEnterTimeout = null;

        // `goto` API function that moves to step given with `el` parameter (by index, id or element),
        // with a transition `duration` optionally given as second parameter.
        var goto = function ( el, duration ) {

            if ( !initialized || !(el = getStep(el)) ) {
                // presentation not initialized or given element is not a step
                return false;
            }

            // Sometimes it's possible to trigger focus on first link with some keyboard action.
            // Browser in such a case tries to scroll the page to make this element visible
            // (even that body overflow is set to hidden) and it breaks our careful positioning.
            //
            // So, as a lousy (and lazy) workaround we will make the page scroll back to the top
            // whenever slide is selected
            //
            // If you are reading this and know any better way to handle it, I'll be glad to hear about it!
            window.scrollTo(0, 0);

            var step = stepsData["impress-" + el.id];

            if ( activeStep ) {
                activeStep.classList.remove("active");
                body.classList.remove("impress-on-" + activeStep.id);
            }
            el.classList.add("active");

            body.classList.add("impress-on-" + el.id);

            // compute target state of the canvas based on given step
            var target = {
                rotate: {
                    x: -step.rotate.x,
                    y: -step.rotate.y,
                    z: -step.rotate.z
                },
                translate: {
                    x: -step.translate.x,
                    y: -step.translate.y,
                    z: -step.translate.z
                },
                scale: 1 / step.scale
            };

            // Check if the transition is zooming in or not.
            //
            // This information is used to alter the transition style:
            // when we are zooming in - we start with move and rotate transition
            // and the scaling is delayed, but when we are zooming out we start
            // with scaling down and move and rotation are delayed.
            var zoomin = target.scale >= currentState.scale;

            duration = toNumber(duration, config.transitionDuration);
            var delay = (duration / 2);

            // if the same step is re-selected, force computing window scaling,
            // because it is likely to be caused by window resize
            if (el === activeStep) {
                windowScale = computeWindowScale(config);
            }

            var targetScale = target.scale * windowScale;

            // trigger leave of currently active element (if it's not the same step again)
            if (activeStep && activeStep !== el) {
                onStepLeave(activeStep);
            }

            // Now we alter transforms of `root` and `canvas` to trigger transitions.
            //
            // And here is why there are two elements: `root` and `canvas` - they are
            // being animated separately:
            // `root` is used for scaling and `canvas` for translate and rotations.
            // Transitions on them are triggered with different delays (to make
            // visually nice and 'natural' looking transitions), so we need to know
            // that both of them are finished.
            css(root, {
                // to keep the perspective look similar for different scales
                // we need to 'scale' the perspective, too
                transform: perspective( config.perspective / targetScale ) + scale( targetScale ),
                transitionDuration: duration + "ms",
                transitionDelay: (zoomin ? delay : 0) + "ms"
            });

            css(canvas, {
                transform: rotate(target.rotate, true) + translate(target.translate),
                transitionDuration: duration + "ms",
                transitionDelay: (zoomin ? 0 : delay) + "ms"
            });

            // Here is a tricky part...
            //
            // If there is no change in scale or no change in rotation and translation, it means there was actually
            // no delay - because there was no transition on `root` or `canvas` elements.
            // We want to trigger `impress:stepenter` event in the correct moment, so here we compare the current
            // and target values to check if delay should be taken into account.
            //
            // I know that this `if` statement looks scary, but it's pretty simple when you know what is going on
            // - it's simply comparing all the values.
            if ( currentState.scale === target.scale ||
                (currentState.rotate.x === target.rotate.x && currentState.rotate.y === target.rotate.y &&
                 currentState.rotate.z === target.rotate.z && currentState.translate.x === target.translate.x &&
                 currentState.translate.y === target.translate.y && currentState.translate.z === target.translate.z) ) {
                delay = 0;
            }

            // store current state
            currentState = target;
            activeStep = el;

            // And here is where we trigger `impress:stepenter` event.
            // We simply set up a timeout to fire it taking transition duration (and possible delay) into account.
            //
            // I really wanted to make it in more elegant way. The `transitionend` event seemed to be the best way
            // to do it, but the fact that I'm using transitions on two separate elements and that the `transitionend`
            // event is only triggered when there was a transition (change in the values) caused some bugs and 
            // made the code really complicated, cause I had to handle all the conditions separately. And it still
            // needed a `setTimeout` fallback for the situations when there is no transition at all.
            // So I decided that I'd rather make the code simpler than use shiny new `transitionend`.
            //
            // If you want learn something interesting and see how it was done with `transitionend` go back to
            // version 0.5.2 of impress.js: http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js
            window.clearTimeout(stepEnterTimeout);
            stepEnterTimeout = window.setTimeout(function() {
                onStepEnter(activeStep);
            }, duration + delay);

            return el;
        };

        // `prev` API function goes to previous step (in document order)
        var prev = function () {
            var prev = steps.indexOf( activeStep ) - 1;
            prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ];

            return goto(prev);
        };

        // `next` API function goes to next step (in document order)
        var next = function () {
            var next = steps.indexOf( activeStep ) + 1;
            next = next < steps.length ? steps[ next ] : steps[ 0 ];

            return goto(next);
        };

        // Adding some useful classes to step elements.
        //
        // All the steps that have not been shown yet are given `future` class.
        // When the step is entered the `future` class is removed and the `present`
        // class is given. When the step is left `present` class is replaced with
        // `past` class.
        //
        // So every step element is always in one of three possible states:
        // `future`, `present` and `past`.
        //
        // There classes can be used in CSS to style different types of steps.
        // For example the `present` class can be used to trigger some custom
        // animations when step is shown.
        root.addEventListener("impress:init", function(){
            // STEP CLASSES
            steps.forEach(function (step) {
                step.classList.add("future");
            });

            root.addEventListener("impress:stepenter", function (event) {
                event.target.classList.remove("past");
                event.target.classList.remove("future");
                event.target.classList.add("present");
            }, false);

            root.addEventListener("impress:stepleave", function (event) {
                event.target.classList.remove("present");
                event.target.classList.add("past");
            }, false);

        }, false);

        // Adding hash change support.
        root.addEventListener("impress:init", function(){

            // last hash detected
            var lastHash = "";

            // `#/step-id` is used instead of `#step-id` to prevent default browser
            // scrolling to element in hash.
            //
            // And it has to be set after animation finishes, because in Chrome it
            // makes transtion laggy.
            // BUG: http://code.google.com/p/chromium/issues/detail?id=62820
            root.addEventListener("impress:stepenter", function (event) {
                window.location.hash = lastHash = "#/" + event.target.id;
            }, false);

            window.addEventListener("hashchange", function () {
                // When the step is entered hash in the location is updated
                // (just few lines above from here), so the hash change is 
                // triggered and we would call `goto` again on the same element.
                //
                // To avoid this we store last entered hash and compare.
                if (window.location.hash !== lastHash) {
                    goto( getElementFromHash() );
                }
            }, false);

            // START 
            // by selecting step defined in url or first step of the presentation
            goto(getElementFromHash() || steps[0], 0);
        }, false);

        body.classList.add("impress-disabled");

        // store and return API for given impress.js root element
        return (roots[ "impress-root-" + rootId ] = {
            init: init,
            goto: goto,
            next: next,
            prev: prev
        });

    };

    // flag that can be used in JS to check if browser have passed the support test
    impress.supported = impressSupported;

})(document, window);

// NAVIGATION EVENTS

// As you can see this part is separate from the impress.js core code.
// It's because these navigation actions only need what impress.js provides with
// its simple API.
//
// In future I think about moving it to make them optional, move to separate files
// and treat more like a 'plugins'.
(function ( document, window ) {
    'use strict';

    // throttling function calls, by Remy Sharp
    // http://remysharp.com/2010/07/21/throttling-function-calls/
    var throttle = function (fn, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    };

    // wait for impress.js to be initialized
    document.addEventListener("impress:init", function (event) {
        // Getting API from event data.
        // So you don't event need to know what is the id of the root element
        // or anything. `impress:init` event data gives you everything you 
        // need to control the presentation that was just initialized.
        var api = event.detail.api;

        // KEYBOARD NAVIGATION HANDLERS

        // Prevent default keydown action when one of supported key is pressed.
        document.addEventListener("keydown", function ( event ) {
            if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
                event.preventDefault();
            }
        }, false);

        // Trigger impress action (next or prev) on keyup.

        // Supported keys are:
        // [space] - quite common in presentation software to move forward
        // [up] [right] / [down] [left] - again common and natural addition,
        // [pgdown] / [pgup] - often triggered by remote controllers,
        // [tab] - this one is quite controversial, but the reason it ended up on
        //   this list is quite an interesting story... Remember that strange part
        //   in the impress.js code where window is scrolled to 0,0 on every presentation
        //   step, because sometimes browser scrolls viewport because of the focused element?
        //   Well, the [tab] key by default navigates around focusable elements, so clicking
        //   it very often caused scrolling to focused element and breaking impress.js
        //   positioning. I didn't want to just prevent this default action, so I used [tab]
        //   as another way to moving to next step... And yes, I know that for the sake of
        //   consistency I should add [shift+tab] as opposite action...
        document.addEventListener("keyup", function ( event ) {
            if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
                switch( event.keyCode ) {
                    case 33: // pg up
                    case 37: // left
                    case 38: // up
                             api.prev();
                             break;
                    case 9:  // tab
                    case 32: // space
                    case 34: // pg down
                    case 39: // right
                    case 40: // down
                             api.next();
                             break;
                }

                event.preventDefault();
            }
        }, false);

        // delegated handler for clicking on the links to presentation steps
        document.addEventListener("click", function ( event ) {
            // event delegation with "bubbling"
            // check if event target (or any of its parents is a link)
            var target = event.target;
            while ( (target.tagName !== "A") &&
                    (target !== document.documentElement) ) {
                target = target.parentNode;
            }

            if ( target.tagName === "A" ) {
                var href = target.getAttribute("href");

                // if it's a link to presentation step, target this step
                if ( href && href[0] === '#' ) {
                    target = document.getElementById( href.slice(1) );
                }
            }

            if ( api.goto(target) ) {
                event.stopImmediatePropagation();
                event.preventDefault();
            }
        }, false);

        // delegated handler for clicking on step elements
        document.addEventListener("click", function ( event ) {
            var target = event.target;
            // find closest step element that is not active
            while ( !(target.classList.contains("step") && !target.classList.contains("active")) &&
                    (target !== document.documentElement) ) {
                target = target.parentNode;
            }

            if ( api.goto(target) ) {
                event.preventDefault();
            }
        }, false);

        // touch handler to detect taps on the left and right side of the screen
        // based on awesome work of @hakimel: https://github.com/hakimel/reveal.js
        document.addEventListener("touchstart", function ( event ) {
            if (event.touches.length === 1) {
                var x = event.touches[0].clientX,
                    width = window.innerWidth * 0.3,
                    result = null;

                if ( x < width ) {
                    result = api.prev();
                } else if ( x > window.innerWidth - width ) {
                    result = api.next();
                }

                if (result) {
                    event.preventDefault();
                }
            }
        }, false);

        // rescale presentation when window is resized
        window.addEventListener("resize", throttle(function () {
            // force going to active step again, to trigger rescaling
            api.goto( document.querySelector(".step.active"), 500 );
        }, 250), false);

    }, false);

})(document, window);

// THAT'S ALL FOLKS!
//
// Thanks for reading it all.
// Or thanks for scrolling down and reading the last part.
//
// I've learnt a lot when building impress.js and I hope this code and comments
// will help somebody learn at least some part of it.

Add this to the directory listed above. At the time of this writing, this is new newest realease of Impress.js. In order to get Impress and Rails to cooperate, I changed my application.html.erb file to this:

view/layouts/application.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
  <title>Thanksyou</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
  <link href='http://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
</head>
<body>
 
<%= yield %>

<%= javascript_include_tag "application" %>
</body>
</html>

That is pretty much it, however I ran into difficulty determining where and when to load the impress.js file. I tried moving it into several different directories including the index view with both the javascript_include_tag and the script tag. I also messed with the load order of the application.js asset pipeline. After fretting for far too long, I put the file in the correct place and all was well. I hope this post saves someone whom wants to play with Impress.js time and energy.

Also, the tutorial is very well written and worth reading for anyone that wants to use this library.

Client Side Validations

| Comments

The Railscast for the Client Side Validations Gem is very outdated and does not function. Furthermore, the documentation for the gem did not completely work with my version of Rails, 3.2.13. The point of this post is to get front end validations to work with Rails 3.2.13.

gem ‘client_side_validations’

$ rails g client_side_validations:install

The file below is created, but you must uncomment lines 10 through 16 in order to get it to work.

config/initializers/client_side_validations.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# ClientSideValidations Initializer

# Uncomment to disable uniqueness validator, possible security issue
# ClientSideValidations::Config.disabled_validators = [:uniqueness]

# Uncomment to validate number format with current I18n locale
# ClientSideValidations::Config.number_format_with_locale = true

# Uncomment the following block if you want each input field to have the validation messages attached.
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  unless html_tag =~ /^<label/
    %{<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>}.html_safe
  else
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
  end
end

//= require rails.validations
...in applications.js
...and the following to your form.

_form.html.erb
1
<%= form_for @user, :validate => true do |f| %>


And a little CSS...


application.css
1
2
3
4
5
.field_with_errors .message {
  color: #FFC200;
  padding-left: 10px;
  display: inline;
}

Your app should now be able to display Rails error messages in line with your form fields. This is where I began to run into problems, creating a custom validator.


The Github Documentation says to put the following code into app/validators/email_validator.rb


initializers/email_validator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      record.errors.add(attr_name, :email, options.merge(:value => value))
    end
  end
end

# This allows us to assign the validator in the model
module ActiveModel::Validations::HelperMethods
  def validates_email(*attr_names)
    validates_with EmailValidator, _merge_attributes(attr_names)
  end
end

This did not work for me. However, creating the email_validator.rb file under the initializers directory did the trick. I need to ask a Flatiron School compadre why this is. Follow the rest of the custom validator documentation for awesome validations. I hope this saves people time while implenting this gem.