A simple Tweet Retweeter

Leave a comment

Hi Guys, So well on a lazy saturday afternoon, when you don’t have anything to do, you get this feeling to make something. So well what you do, you just make something simple, Burgers, fast food anything that you like. But well people like us who think, they are so called developers, have to feel the burden of creating something which which solve more a problem more important than the “What to have for lunch?” problem.

Anyways, so well, I have two twitter accounts, 1) @sudipto05 <– which I use and do follow me here and 2) @delhianimeclub which is my club’s twitter accout, which well, I never use, but well, its gets updated with the posts that are put on our facebook page. (If you are into anime, do like us on facebook). So the problem at hand, I had to manually retweet the tweets of @delhianimeclub from my other account, you know cross promotion, stuff like that. But this wasn’t really cool. right?

So what do Rails developers do?

This is what they do

rails new retweeter

Lets add a few gemfiles, of late I have had to work on HAML and Bootstrap so lets add those gems. Checkout my gemfile from link. We wont be really needing the twitter bootstrap gem for this iteration of the project, but we will be certainly using it for the making a statistics application for our twitter account. I don’t really like postgresql, but I wanted to host it on heroku,which only has support for pg. Oh yes, just forgot, two of the most important gems that we are going to use

1. Twitter gem – will let us post fetch and post tweets only with what 2 lines of code! I could have tried to use Twitter’s rest api too, but then, who is going to make lunch? huh?

2. Rufus Scheduler – I love this, its an awesome gem for scheduling your jobs, since we are going to check if new tweets are posted after regular intervals, we need some kind of cron job running behind our app, this is going to make it super easy.

After adding the gem files, just

bundle install

So here we go, now some actual coding starts, well yeah! twitter bootstrap gem doesnt like windows at all, so its better if you add the css and js files manually from link. You know right? they go into the assets folder 😛

Well, we are going to save the tweets in our database too, so lets generate a Tweet model with three fields.

rails g model Tweet tweet_id:string tweet_text:string tweeted_at:datetime

The advantage of specifying the attributes while generating a model is that they get automatically added to both the migration! duh! and also in the attr_accessible in the model file. Saves you 10 seconds of typing 😛

and afterwards to run the migration and setup our database

rake db:migrate

lets start with our Scheduler first. Create a new file in the config -> initializers directory, well you can name it anything, I just named it task_scheduler.rb and put in the snippet of code. A very simple explanation of the code within the file.

1) Requires the rufus scheduler gem, so we add the require line.

2) Create a new instance of the scheduler with

scheduler = Rufus::Scheduler.start_new

3) And lastly we simply call a class method within a block, which will call the method every 1 minute, now you can choose the duration of the interval according to your needs, 1 minute seems fair enough, its not like we post tweets faster. What? It requires aesthetics for tweeting? huh?

Okay so we are done with 33% percent of the work, Lets move onto our model file, Remember Tweet model that we created. Check out the file from link. Lets see what gibberish we have to put in the code now.

1. First we get the recent tweets of the user from whose account, we are going to retweet. latest_tweets = Twitter.user_timeline(“account_name”)

2. Then we run a simple loop through the recent tweets that we get from twitter and check if the tweet is present in the database, if not, the tweet will be retweeted and saved in the database.

3. Every tweet has its unique id which you can access using Tweet.attrs[:id] or Tweet.attrs[:id_str] which has the same value as :id_str, just use anyone you like, the twitter api says to not use the @attrs[:id] but thats applicable only for javascript code.

4. Oh yes! I have put this whole block of code within begin rescue end block, this twitter gem seems to throw in some weird exceptions sometimes, so just to log the errors, you can use the logger of your choice for this.

Okay, Guess we are done with 70% of the work 😀

So the next step is to create a new twitter application which is going to be used to post your tweets, don’t worry, we just need it for the config keys, nothing fancy.

1. Head over to link, to create a new twitter application. Oh yeah! sign in with the twitter account, using which you want to retweet the tweets from your other account.

2. Fill in the name and all description, just anything who cares 😛

3. After you are done with creating the app, go to settings and change the application type to “Read and Write” after this change save it and head back to the Details tab and create new access tokens. What? can’t you see, there is a button on the bottom to create new tokens.

These tokens will be used to authorize our rails app to post the tweets, oh yeah! the name you put for this app is going to show below every tweet 😛

You need to add these keys to your environments.rb file. Just check out the files here and add the lines for twitter config to the respective environment file in your app.

And we are done, just start the server and see the magic. Our initializer will run after 1 minute and fetch the latest tweets, save them in database and post them to our other twitter account. Thats it. What we have made a retweeter in less than what 30 lines of code, i guess, that is why I love ruby on rails. Oh! wait, you are going to tell me, that I made a rails app, just for this, when I could have done this using just a single ruby file, well yeah! the reason being, we are going to extend this web application in many many ways, so don’t forget to check the blog for updates. The code of this application is hosted on my github.

Advertisements

A funny but scary problem

Leave a comment

Now this is funny and scary at the same time. I ran into a problem which well, most of you(actually even me would term as stupid). This post is however not to show display my stupidity but something else.

Here is a snippet of code for taking an user input.

<p>Register if you wish to receive updates about the broadcast.</p>

<input type="text" id="email_address" />

<input type="submit" value="SUBMIT" class="submitBt" onclick="register();" />

Now what this piece of code does is, take an input (email) from the user and when the user clicks on the user a register() function is called which takes the email and sends it to the database.


function register() {

var email_address = document.getElementById("email_address").value;

$.ajax({

url: 'http://127.0.0.1/test/sendregistration.php/',

type: 'POST',

data: {

query: data_

},

success: function(data)

{

window.location = "http://127.0.0.1/test/tq.html";

}

}

Now what was the problem with this code. I tried to figure it out for like 4-5 hours. Very simple javascript, nothing wrong with it. Takes the data that the user types in the input area and the register() function is called when the button is clicked. Stuff that was bothering me more was, it was working perfectly in firefoz but not in chrome. why? WHY? WHYYY??

So you see, what I am doing here is –

1. On the click of the button, I am submitting the form as well as calling the javascript function.

2. Now well, since I haven’t given any action method, so where is it going to submit, ofcourse to the same page, duh!

3. So firefox called the register() function first, which in turn changed the window.location to our tq.html page, but chrome just called the ajax function and submitted the page, so it just reloaded.

Well! I was looking too hard at the javascript and not at the html code. Had I looked at the HTML, I might have found the problem soon. Small things in life that make you smile and small coding horror like this can make you wanna break your keyboard 🙂

Choose the db adapter while creating a new application in rails

Leave a comment

A lot of people are moving towards Ruby on Rails even at corporate level and giving up the standard Java, .Net way of developing websites for their customers. There are plenty of reasons for that, one of them being their argument that these languages are good at small level but are not scalable enough to solve the needs of corporate level customers. But now even developers who have been coding in java or other languages are increasing looking at solving their problems using frameworks such as Rails or Python/Django.  I believe the development curve of any language is steep only because of the time you want to devote to that language. I chose to devote some time to learn a few things in rails that makes life easy or atleast saves a bit of time. So lets see. lets make some rails stuff.

You would know that to create a new application all you need to do is type


rails new application_name

But this configures the application to use the sqlite3 database, If you want to use any other database, you would have to change it manually in the config->database.yml file. But there is a better way to do it, If you are sure, what database you are going to use, you can just specify it at the time to creating the application


rails new application_name -d mysql

The “-d” specifies the database name, you can use any of the databases from the list – mysql, oracle, postgresql, sqlite3, frontbase, ibm_db, sqlserver, jdbcmysql, jdbcsqlite3, jdbcpostgresql, jdbc.

No Ruby Version Manager on Windows.

Leave a comment

Its true that there is no ruby version manager on windows, which makes life really difficult for a lot of ruby or rails developers I am sure, Well it did for me at least. A lot of applications developed in version 1.8.7 aren’t compatible with the new version. A lot of applications also fix themselves to use only specific versions of ruby, so there is not much we can do, unless you are a mega-geek and can change a lot of things and ofcourse have a lot of time. On linux we always have had RVM to solve this problem which lets us have different versions of ruby, different gemsets for each version of ruby, makes life really easy. But what for the windows developers? Thankfully a noble soul known as Gordon Thiesfeld made something amazing known as pik. which essentially works the same as Ruby version manager, with a few differences in installations but none in usage. Both of them are equally easy to use.

I am not going to write about how to install and use RVM, since there is enough help for that on the WWW. But Since I love windows users(I being one). We will have a walk-through with pik today. Before we start you can have a look at the github page of the project – https://github.com/vertiginous/pik

Installations –

It does mention that you need to install ruby 1.8.7 first to install pik, Now ruby 1.8.7 is an older version and I wonder, why would I need to install an older version to install a newer version, So first I went ahead and installed ruby 1.9.2-p290 from http://rubyinstaller.org/downloads/ for installing pik. Seems it worked just fine. You can choose to install ruby 1.8.7 first and then install pik, its entirely upto you.

After installing Ruby make sure, you also have devkit installed, if you are a windows user you would know that ofcourse, dev kit is used to build the gems that are developed with native extensions, which means nothing, but those gems are made partially in ruby and partially using c. You can’t miss C anywhere can you. Anyways, I will give a quick guide about installing devkit, since you are going to need it anyways.

Head over to http://rubyinstaller.org/downloads/ and download DevKit.
Installations steps
1. The file you downloaded is just an extractor, extract is to somewhere where you wont delete it by mistake.
2. After extraction, open up CMD and cd to the location where you extracted the files.
3. run

ruby dk.rb init

4. This will let you know the ruby installed in your system.
5. run

ruby dk.rb install

and you are done. Didn’t take too much time, did it?

Now we move on to pik installation steps
1. Fire up CMD and run

gem install pik

2. Now if you type

pik list

you will be able to see that it shows the base version of ruby that you installed. In my case, it shows

* 192: ruby 1.9.2p290 (2011-07-09) [i386-mingw32]

3. There are two ways of adding ruby versions to pik, either you install them manually and add to pik or you just install them through pik. We will see how to install them from pik, since we are going to use pik anyway, less bothersome to do it from pik, than downloading from the internet, installing each of them and then adding to pik.
4. Installing other version of ruby

pik install ruby 1.8.7

And here you go it will install the version of ruby and add that to pik by itself, Less of a hassle. right?
5. Check the versions of ruby installed in your system

pik list

6. Change the version of ruby that you want to use

pik use ruby [verions]

in my case

pik use ruby 1.8.7

7. Don’t forget to use the help if you get stuck.

pik help commands

A Delay?

Leave a comment

Yeah! sad at it is, I wasn’t able to write any code for OneWeek of Awesomeness (What’s it? Read here).

Why?

Well, its like, On Monday, I came to know that I had an interview on Thursday and didn’t want to miss the Interview and the job. Now that I think back, the interview was really very easy, except for some questions which I have no idea, how should I have answered them. Like one of them was.

What is the difference between :resource and :resources in rails.

hu hu :3 I have no bloody idea, what’s the difference.

Another of them was, How do you remove files from github?

I was like eh, Never deleted any files, IDK maybe just remove it locally and push the changes, that might remove it. So well, apparently you cant remove files that that, for that you got to use

git rm <—to remove

heh! I said, Never needed to delete3 any file, since I always worked with as minute branches as possible and only committed after it ran successfully.

Anyways, I had kind of three interviews, but then only the first one was technical, the other two were just discussions about my college life. Heck, I kind of told my third interviewer that I had a lot of trouble finding this office, since it was not in Google Maps. I SHOULDN’T have said that, since she is VP – operations Technology and India Operations. Man!! But well she was very nice, so I guess, its all cool. Nothing too much to bother about.

So well, I got the job, they are not paying me, what I asked for, but then, who cares, I will get enough money to make my own cosplay and not buy it from eBay, since the Anime Convention is in September this year, Gotta Cosplay!!

Anyways, the joining is from Tomorrow only, that’s Monday, 23rd July. I will keep on working on this OneWeek of Awesomeness and I guess, now it might stretch to 2-3 weeks, But it cannot be helped.

So well, stay tuned, First day of office tomorrow, I hope they don’t kick me out. ^_^

SASS to CSS

Leave a comment

Normally, Every web developer is accustomed to use CSS, but as simple it might be to write CSS, SASS provides a few benefits, that are difficult to miss. Benefits like?

First Things First, Why is Sass called Syntactically Awesome Stylesheets.

Now people who would have used haml to define their views for rails applications would strike a chord with sass in an instant. Why? because sass takes its style of syntax from haml itself. nested elements. Now I do use sass for my rails applications, but It doesnt mean its limited to rails only,  you can use it anywhere you have to use css, I personally use it for generating css files for sencha touch too.

Example Sass File

.tweet-wrapper {
  h2 { font-weight: bold; padding-bottom: 3px; }
  img { border-radius: 5px; float: left; }
  .tweet { font-size: 70%; margin-left: 60px; min-height: 50px; }
  .posted { float: right; }
}

Sass converted to CSS

/* line xx, styles/default-theme.scss */
.tweet-wrapper h2 {
  font-weight: bold;
  padding-bottom: 3px;
}
/* line xx, styles/default-theme.scss */
.tweet-wrapper img {
  border-radius: 5px;
  float: left;
}
/* line xx, styles/default-theme.scss */
.tweet-wrapper .tweet {
  font-size: 70%;
  margin-left: 60px;
  min-height: 50px;
}
/* line xx, styles/default-theme.scss */
.tweet-wrapper .posted {
  float: right;
}

The “xx” provides the line numbers of the sass file, from which the css is generated. Nifty feature to debug, if you made some error, because SASS files tend to get lengthy, but well, less than your CSS files atleast.

Now there are two of the basic ways, in which you can compile SASS/SCSS to CSS files, one of them being the sass way, and another being using Compass.

1. Add this to your gem file and do a Bundle Install

gem "sass", "~>; 3.1.18"

2. From your command line/terminal, type

sass --watch style.scss:style.css

This will invoke the sass executable that got installed from the gem and will create your stylesheet in CSS, pretty easy, right?

The second way of generating CSS from SASS is by using Compass, which I use too. The reason you would like it better too is, One its being used by a lot of websites, which you like a lot and More importantly its not always necessary, that you use sass to css only for your rails projects, as I said, you can use it for any other web project.

1. Well, if you are using it for your rails project, just add the below code to your gemfile and run a “Bundle install”, but If not, you can just install the gem compass directly

gem "compass", "~> 0.12.1"

Installing gem directly

gem install compass

Yes, for both the ways, you have to first install ruby to your system.

2. In the directory, where you have your sass file you need to create a config.rb file, which compass uses to expand your sass to css.

# get the firectory that this configuration file exists in
dir = File.dirname(__FILE__)

# Load the sencha touch framework
load File.join(dir, '..', 'touch', 'resources', 'themes')

#look for any *.scss files in the same directory as this file
#place compiled *.css files in the parents drecotory
sass_path = dir
css_path = File.join(dir, "..")
output_style = :expanded        # change it to :compressed, if you want a small size compressed file
environment = :development      # change it to :production , if you want a small size compressed file

3. Now from the Terminal, change your working directory to the one where you have yous sass file and run

compass compile

4. When you are still add code to your sass file, you can instead choose to make compass watch your sass file and auto generate css whenever you make any changes.

compass watch

Autotest Problems

Leave a comment

Here is some problem that I encountered while ruby on rails development. You might know about TDD (Test Driven Development). Now since autotest can be used to speed up and automate the testing process somewhat and spork can be used to reduce the amount of time require d to run the tests. This becomes crucial that your tests are running smoothly.

The problem I encountered was that autotest continuously kept on testing all the cases.  Autotest is supposed to run only when there is any change made to the files that are referred in the test cases. So my autotest wasnt stopping even when I wasnt making any change. Autotest is a CPU intensive task, so it was necessary for me to find a workaround so it stops testing again and again till I actually make some changes..

The workaround to stop autotest from running if you dont make any change is  to add these lines to your .autotest file

autotest.add_exception %r{^\./db}
autotest.add_exception %r{^\./log}

My .autotest file looks like

require ‘autotest/growl’ # enable pop-up windows
require ‘autotest/restart’ # optional: forces autotest to pick the changes to this file
require ‘autotest/timestamp’ # optional: shows timestamps for test runs

# filter out VCS files and other garbage to reduce HDD usage

Autotest.add_hook :initialize do |autotest|
%w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|
autotest.add_exception(exception)
autotest.add_exception %r{^\./db}
autotest.add_exception %r{^\./log}
end
end

# do not clear console before running tests
Autotest::Growl::clear_terminal = false

Newer Entries