How to mock file upload with RSpec 3.0 ? [SOLVED]

One more note on RSpec 3.0, this time one useful function that mocks File Upload , saves file/archive content to memory so after it you can do whatever your soul wants with it. Test file/archive should exist in the file system.


def mock_archive_upload(archive_path, type)
  return ActionDispatch::Http::UploadedFile.new(:tempfile => File.new(Rails.root + archive_path , :type => type, :filename => File.basename(File.new(Rails.root + archive_path))))
end

 

e.g of use:


#saves archive into memory so it can be manipulated in tests
mock_archive_upload("../fixtues/my_archive.zip", "application/zip")

Posted in open-source, Programming Languages, Rails, Rspec, Ruby | Tagged , , , , , , | Leave a comment

How to stub File.read in RSpec 3 [RAILS, TDD]?

 

Recently, I have been doing whole bunch of spec rewriting from RSpec 2 to Rspec 3. As a result I have found that documentation is not that straightforward, and some cases you need to really spend time and figure out yourself. So I’ll be posting some cases that I have not been able to find in docs, just as notes for myself, and hopefully it will be useful for someone else.

 

Use Case:

I have JSON file that I need to read, and I already have tests that this JSON file opens properly.  I also have a Validator that looks for certain patterns keys in this JSON file. Validator leaves separately from the main app, and I don’t want to replicate File Upload -> File Save to Cloud -> File Open in my Validator Tests, I just want on every File.read to return certain data, and it does not matter to me what exactly is being read, and if path exists or not.

How would I do it in Rspec ?

data = {:name => "test" , :description => "test"}.to_json
allow(File).to receive(:read).and_return(data)

What does it give you ?

It looks for every File.read in the scope of your spec and instead of actually reading file returns ‘data‘ every time.

Cool, huh ?

:)

Anatoly

Posted in Programming Languages, Rails, Rspec | Tagged , , , , , | Leave a comment

How to stub an IP in Ruby on Rails, RSpec Version 3 ?

Often when you are writing unit tests, you want to mock your IP address. Some of the uses cases could be – you are checking if IP is within the certain range.

For RSpec 2.x  mocking  IP would look like this:

 ActionDispatch::Request.any_instance.stub(:remote_ip).and_return("192.168.0.1")

Taken from here

However, if you try to do it in RSpec 3.x, it will give you an error since ‘any_instance‘ syntax is deprecated.

To make the same work for RSpec 3.x use this:

   allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("192.168.99.225")

Posted in Programming Languages | Tagged , , , , , , | Leave a comment

How to scaffold JavaScript Web Application in seconds using YEOMAN ? (example with Backbone Marionette)

Hey guys,

Today I want to discuss an issue that I have been recently facing, and how to solve it.

The issue is:

How to set up a new JavaScript web app as quickly as possible and start developing, instead of worrying about dependencies and digging into configuration files trying to tie different libraries together ?

If you are a Rails developer, you will understand what I mean. In Rails you can scaffold your application and have a mockup that you can start building on in seconds. I haven’t been able to find such tool for JavaScript web apps… Until now…..

My colleague Tim showed me a tool today, that does the job for you.

The tool is called: YEOMAN .

YEOMAN uses 2 other tools for JavaScript that should be in a must-have list for any JavaScript Web Developer.

They are:

a. Grunt  – JavaScript task runner
b. Bower –  A package Manager for Web

The good thing is that to develop simple Web App with YEOMAN, you don’t even need to know how to use those tools, because YEOMAN does everything for you. However, I highly encourage you to read documentation for both tools, because they will make your JavaScript development SO MUCH EASIER!

Finally, after this long intro, let’s get to setting up our first JavaScript Backbone Marionette application using YEOMAN.

Before you start:

You need to have: Node.JS and NPM. To be honest, if you are planning to develop web apps – you will need them anyway.

You can find how to install Node.JS and NPM here .

When you have Node and NPM in place, you need to:

1. Install Bower and Grunt.  using NPM:

npm install -g grunt-cli
npm install -g bower

Tip: ‘-g’ in npm install makes element that you have installed  – global, so you just need to install it once, and use it  for multiple applications.

2. Install YEOMAN

npm -g install yo

3. Install YEOMAN generator for Marionette.JS

npm install -g generator-marionette

4. Install Mocha Generator that Marionette Generator uses:

npm install -g generator-mocha-amd

5. Create Web App Folder, Scaffold Marionette Application using YEOMAN Generator:

mkdir WebAppTest
cd WebAppTest
yo marionette

Expected output: (If you need any components I said no to, please put Y instead of ‘n':

_-----_
 | |
 |--(o)--| .--------------------------.
 `---------´ | Welcome to Yeoman, |
 ( _´U`_ ) | ladies and gentlemen! |
 /___A___\ '__________________________'
 | ~ |
 __'.___.'__
 ´ ` |° ´ Y `
Out of the box I include HTML5 Boilerplate, jQuery, Backbone.js, Marionette, Handlebars, Require and Modernizr.
 [?] Would you like to install the full express app or simply the marionette generators? Yes
 [?] Would you like to include MongoDB for storage? No
 [?] Would you like to include Socket IO for real time communication? No
 [?] Would you like to include Baucis for REST? No
 [?] Where do you want the Bower components installed? (bower_components) ENTER

Note: this will take a while,  but in the end YEOMAN will create a web app, put all necessary dependences and even tests. Isn’t it amazing ?

6. Run your application:

grunt

This will load your browser and you will be able to see this screen:

Screen shot 2014-02-24 at 12.40.06 PM

So here you have your scaffolded Marionette application that includes Handlebars.JS templates and Unit tests.

Of course it doesn’t stop on Marionette, there are plenty of generators for YEOMAN allowing you to scaffold many web apps of your choice.

That’s it for today,

Try it and let me know how it goes!

Anatoly

Posted in Backbone.JS, Handlebars.JS, JavaScript, Marionette.JS, open-source, Programming Languages | Tagged , , , , , , , | 4 Comments

RAILS, HAML : How to put Checkbox and label on the same line, with translations

Hey guys!

Today I have decided to share with you little secret, that can save you quite some time, while writing templates with HAML.

While creating a form for one of the projects, I needed to put a checkbox within the same line as label and also I had to make my label a “translation”.

I googled and the closest which I was able to find was: http://stackoverflow.com/questions/9774555/nesting-ruby-on-rails-haml-checkbox-in-label-tag

However, It didn’t really solve my “translation” problem.

Initially my code looked like this:

= simple_form_line do
  = f.label t('.send_email')
  = f.check_box :send_email, class: "checkbox"

.send_email in this case is a translation from my eng.yml file which equals to “Send credentials to user by email”.

The code produced this output:

Image

However, what I needed my checkbox and message to be on the same line. This is how I was able to solve it:

= simple_form_line do<
  %label.checkbox{ :for => "send_email" }
    = f.check_box :send_email, class: "checkbox"
    = t(".send_email")

(Sorry if wordpress screwed indentation!!!)

And here is how output looks like:

Image

That’s it for today!

Have a wonderful day!

Regards,

Anatoly

Posted in Programming Languages, Rails | Tagged , , , , , | Leave a comment

How to make a contact form with Bootstrap 3 ? (JQuery/PHP/HTML5/JqBootstrapValidation)

Hey guys!

Today we will talk about such essential feature for any website as contact form. Recently, while working on one of the projects, I had a pleasure combining couple of very nice tools (Bootstrap 3 + JQuery + jqBootstrapValidation), which resulted in minimalistic , but powerful contact form, that would be a good addition to any website.

Contact me form

VIEW DEMO          CODE

In this post I will walk you through the process of developing this form. Also if you just want to put it in your website, just pulled from my github repo and have fun.

Sounds good ?

Let’s start.

When I was developing my form I had in mind following goals:

- Minimalistic design
– Track person’s contacts for future communication
– Send form information directly to my email
– Validate input – client side and server side
– Show success when form is sent, or provide alternative method if something went wrong

As you might see – nothing special. I would love if somebody else would provide me this solution yesterday, when I was working on my project – this could save me some time! :)

Let’s divide our workflow into sections:
– Required Libraries
– UI
– Client-side Validation, JQuery – PHP Interaction
– PHP (so called server side)

Required Libraries

We will require following libraries :
Botostrap 3
–  jqBootstrapValidation

So all you need to do is just download necessary files and put them in.

After getting Bootstrap and jqBootstrapValidation our website tree will look like this:

-
– –  css
– – – bootstrap.min.css
– – js
– – – bootstrap.min.js
– – – jqBootstrapValidation.js

Let’s move to the UI part.

UI

For the UI we will use Bootstrap 3 and some attributes from jqBootstrapValidation.js . I won’t cover Bootstrap 3 components as it will take far too long, but if something is unclear, please shoot me an email and I will clarify that for you.

So in the root of our website we need to create file form.html .

Final version of /form.html will look like this:




Contact form for your site by Anatoly Spektor
  <!-- Bootstrap CSS -->
  	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen" />


<!-- Contacts --></pre>
<div id="contacts">
<div class="row"><!-- Alignment -->
<div class="col-sm-offset-3 col-sm-6">
      <!-- Form itself -->
<form class="well" id="contactForm" name="sentMessage" novalidate="">Contact me
       <!-- Full Name -->
<div class="control-group">
<div class="controls">
	    <input class="form-control" id="name" type="text" placeholder="Full Name" required="" data-validation-required-message="Please enter your name" />

</div>
</div>
        <!-- Email -->
<div class="control-group">
<div class="controls">
		<input class="form-control" id="email" type="email" placeholder="Email" required="" data-validation-required-message="Please enter your email" /></div>
</div>
        <!--Message -->
<div class="control-group">
<div class="controls"></div>
</div>
<div id="success"></div>
 <!-- For success/fail messages -->
 <button class="btn btn-primary pull-right" type="submit">Send</button>

</form></div>
</div>
</div>
<pre>
 <!-- JS FILES -->

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script type="text/javascript" src="./js/jqBootstrapValidation.js"></script><script type="text/javascript" src="./js/contact_me.js"></script>




Sorry for this formatting, it’s hard to put code into WP, please find formatted version of form.html here

If you are familiar with Bootstrap – this code is pretty straightforward.

There are couple of important things I would like to point out:

  1. Since we are using jqBootstrapValidation, we need to put novalidate attribute into our form tag, otherwise HTML5 validation will clip jqBootstrapValidation validation.
  2. To change color/style of your error messages just change “.help-block” CSS class
  3. data-validation-* classes are used to specify custom message when user does something incorrectly. You can find more about those here.
  4. jqBootstrapValidation library looks at input and textarea tags and automatically puts validation if needed. For example if there is a “required” attribute, it automatically will put error message if the field is empty.

That’s all I can think of, if you have additional questions, please send me an email, or ask me in the comments below the post.

Client-side Validation, JQuery – PHP Interaction

So now we have finished the design of our form. Next step is to activate jqBootstrapValidation library, pass users data to PHP, which will send an email and finally show something to the user.

Most of these is done in one tiny JQuery function.

Here it is (file js/contact_me.js):

/*
  Jquery Validation using jqBootstrapValidation
   example is taken from jqBootstrapValidation docs
  */
$(function() {

 $("input,textarea").jqBootstrapValidation(
    {
     preventSubmit: true,
     submitError: function($form, event, errors) {
      // something to have when submit produces an error ?
      // Not decided if I need it yet
     },
     submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit haviour
       // get values from FORM
       var name = $("input#name").val();
       var email = $("input#email").val();
       var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
           // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
	   firstName = name.split(' ').slice(0, -1).join(' ');
         }
	 $.ajax({
                url: "./bin/contact_me.php",
            	type: "POST",
            	data: {name: name, email: email, message: message},
            	cache: false,
            	success: function() {
            	// Success message
            	   $('#success').html("</pre>
<div class="alert alert-success">");
 $('#success > .alert-success').html("<button class="close" type="button" data-dismiss="alert">×")
 .append( "</button>");
 $('#success > .alert-success')
 .append("<strong>Your message has been sent. </strong>");
 $('#success > .alert-success')
 .append('</div>
<pre>
');

 		  //clear all fields
 		  $('#contactForm').trigger("reset");
 	      },
 	   error: function() {
 		// Fail message
 		 $('#success').html("</pre>
<div class="alert alert-danger">");
 $('#success > .alert-danger').html("<button class="close" type="button" data-dismiss="alert">×")
 .append( "</button>");
 $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly to <a href="'mailto:me@example.com?Subject=Message_Me">me@example.com</a> ? Sorry for the inconvenience!");
 $('#success > .alert-danger').append('</div>
<pre>
');
 		//clear all fields
 		$('#contactForm').trigger("reset");
 	    },
           })
         },
         filter: function() {
                   return $(this).is(":visible");
         },
       });

      $("a[data-toggle=\"tab\"]").click(function(e) {
                    e.preventDefault();
                    $(this).tab("show");
        });
  });

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
     $('#success').html('');
  });

For the most part I have took the function from jqBootstrapValidation examples. However, there are couple of things particularly interesting to us.

jqBootstrapValidation allows to overwrite submit on success behaviour, which I am doing in this case. If user submits everything without errors – I do a POST request to the file bin/contat_me.php with name, email and message.

File contact_me.php, which we will code in the next section, sends me an email with everything that user filled in. Also, I check If I am able to connect to this file, in this case I send back “Message sent successfully” to the user, otherwise I give an error telling user to email me directly ( use cases: for example if mail server is down, if validation on server side failed, if permissions to php file are incorrect etc) .

There is not much to add, but if you have any questions regarding this function do not hesitate to ask.

PHP (so called server side)

Finally, we got to the last piece of this puzzle. I have a php file that does some validation on the data received from form and sends me an email.

Here is my PHP file ( bin/contact_me.php )

<?php 
// check if fields passed are empty 

 if(empty($_POST['name'])   ||    
    empty($_POST['email'])  ||
    empty($_POST['message'])||   
    !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))    
  { 	
       echo "No arguments Provided!"; 	return false;    
  } 
	
  $name = $_POST['name']; 
  $email_address = $_POST['email']; 
  $message = $_POST['message']; 	 

 // create email body and send it	 
 $to = 'me@myprogrammingblog.com'; 
 // put your email 
 $email_subject = "Contact form submitted by:  $name"; $email_body = "You have received a new message. \n\n". 				  
                   " Here are the details:\n \nName: $name \n ". 				  
                   "Email: $email_address\n Message \n $message"; 
 $headers = "From: contacts@myprogrammingblog.com\n"; 
 $headers .= "Reply-To: $email_address";	 

 mail($to,$email_subject,$email_body,$headers); return true;			 
?>

As you might see my PHP file is even more simple. Of course you can add extra validation on top of it. For my use case I am just checking if fields are not empty and if email has correct format. If everything is correct, I create an email and use PHP’s mail function to email it.

That’s it.

You can find all these files here.

I hope this function will be useful for you!

Regards,

Anatoly

Update:

F.A.Q

(Thanks a lot to Corey Russell  for resolving some of the occurring issues)

Q:  I see “Sorry <Name> it seems that my mail server is not responding… Could you please email me directly to….”

A:  1. Go to line 26 of the contact_me.js file you have. There you’ll see the url for contact_me.php. Make sure that url is correct. I think by default it is pointing to a folder called bin.
2. If you try it from your desktop it won’t work as it doesn’t have a php server/client installed.

 

Posted in Bootstrap, HTML5, JavaScript, Jquery, open-source, Programming Languages | Tagged , , , , , | 151 Comments

How to find if a number is power 2 ? (Bitwise and Iterative) [Python Script]

As I have promised, I continue answering your questions.

One of the readers of myprogrammingblog.com wrote me an email asking How to find if a number is power 2 ? He also asked me to write a bitwise solution as well as an iterative  solution using Python. There are many examples of these kind of questions in the Internet, but I thought it would be nice to put one up here too,  since person asks.

Ok, here we go !

So first solution  is the bitwise one .

In this solution we will be using legendary bitwise operator AND (&). This solution is based on the unique property of all power 2 numbers having only one bit set to one and all other bits to zero. So number-1 will remove this one bit making expression equal to zero, if the number is power of two. You will notice that there is special case – number != 0 . If you put 0 into expression below, you will see that despite 0 being not power of two, expression will return true. So to eliminate special case, I just made sure that number is not zero.

Here is the function itself :

# Bitwise version
def powTwoBit(number):
  return (number & (number-1) == 0) and (number != 0)

Second solution is easier to understand if you are not a big fan of bitwise operations, since it uses regular looping and is based on the property that any number that is power of two has –  divisible by two without a remainder. So in this solution I loop and divide number by 2 until number is not equal to 1. If one of these divisions shows me that division produced a remainder, I know that number is not power of two. I also take into account special case – number must be positive.

#Iterative version
def powTwoIter(number):
	isPowOfTwo=True;
	while (number != 1 and number > 0):
		if(number%2):
			# can do return here as well
			isPowOfTwo = False
		number=number/2
	return isPowOfTwo and (number > 0)

So here they are – 2 solutions of how to find if a number is power of 2 in Python. I have put this code into myprogrammingblog.com github repo together with Unit Tests. So feel free to use it.

Of course there are many other solutions. For example you can create an array of power 2 values, sorted from least to greatest (the range that corresponds to the problem you are trying to solve) and use a binary search to find if your number corresponds to one of those in the array.

 Choose whatever works for you!

Regards,

Anatoly

Posted in open-source, Programming Languages, Python, Useful Functions | Tagged , , , , | Leave a comment