Category Archives: Ruby

Push to IMGUR and get tiny url with RUby

After a long absence from blogging snippet of code or anything interesting (lately I was kind of busy with work and personal issues to solve), I’d like to share with you something that I created months ago but I hadn’t the time to publish: a ruby code to publish new images to imgur.

As you can find on WikipediaImgur is an online image hosting service founded by Alan Schaaf in 2009 in Athens, Ohio (not Greece as I imagined first by reading it). Imgur describes itself as “the home to the web’s most popular image content, curated in real time by a dedicated community through commenting, voting and sharing. It offers free image hosting to millions of users a day, and a comment-based social community.

So far so good, but how can we interact with it? Imgur exposes APIs to interact with the entire Imgur infrastructure via a standardized programmatic interface. Using Imgur’s API, you can do just about anything you can do on imgur.com, while using your programming language of choice, in my case Ruby.

Lets move ahead! First of all you need to register to have an account, then navigate to the imgur API http://api.imgur.com and read the documentation. The following step consist in the creation of the API KEY.

Under settings > applications click on create you own

image

And register you application:

image

For tests purposes just pick random values, in my case:

Application name: imgTest
Authorization type: OAuth authentication without callback
Email:myemail@degiorgi.me
Description: test

Fill the captcha and submit the form.

image

Great! Now you have the Client-ID and the token to perform programmatic access to your account.

#!/usr/bin/env ruby
 
require 'net/http'
require 'net/https'
require 'open-uri'
require 'json'
require 'base64'
 
def web_client
  http = Net::HTTP.new(API_URI.host, API_URI.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  http
end
 
API_URI = URI.parse('https://api.imgur.com')
API_PUBLIC_KEY = 'Client-ID XXXXXXXXXXXXXX'
 
ENDPOINTS = {
    :image => '3/image',
    :upload => '/3/upload'
}
 
img = File.open("your-image.jpg", "rb") {|io| io.read}
params = {:image =>  Base64.encode64(img),
          :gallery => "gallery",
          :name => "name"
}
 
 
request = Net::HTTP::Post.new(API_URI.request_uri + ENDPOINTS[:image])
request.set_form_data(params)
request.add_field('Authorization', API_PUBLIC_KEY)
 
response = web_client.request(request)
 
puts JSON.parse(response.body)['data']['link']

The JSON response contains the tiny URL to the uploaded image:

http://i.imgur.com/q8AbXIY.jpg

We can improve the code by adding the album and gallery parameters.

In my next post I’ll explain how to automatic post to linkedin accounts using the imgur script and other libraries.

Tagged , ,

Ruby Koala Gem to Interact with Facebook

Today I started playing around with the Koala gem:

https://github.com/arsduo/koala

Koala is a Facebook library for Ruby, supporting the Graph API (including the batch requests and photo uploads), the REST API, realtime updates, test users, and OAuth validation.

To install the gem just:

gem install koala
Or put it in the Gemfile and use the bundle command ‘bundle install’:
gem "koala", "~> 1.8.0rc1"
Before we can connect to Facebook, we need to create an access token for the authentication, go on the following link:
https://developers.facebook.com/tools/explorer
And create your key with user_groups and user_photos privileges.
image
Here the code to post to specific groups, substitute the key with the one you got in the previous step:
#!/usr/bin/env ruby
require 'koala'
 
oauth_access_token = 'xxxxxxxxxxxxxxxxxx'
group_filtering_words = ['gangofruby', 'gangofrubyII']
image_path = 'ruby.jpg' #change to your image path
message = 'Ruby is the most beautiful gem.' # your message
 
graph = Koala::Facebook::API.new(oauth_access_token)
 
# getting groups of interest
groups = graph.get_connections("me", "groups").select do |group|
  group_filtering_words.any? do |word|
    group["name"].downcase.include? word
  end
end
 
 
groups.each_with_index { |group,i|
  puts "[#{i+1}/#{groups.size}] Posting to group #{group["name"]}."
  graph.put_picture( image_path, {message: message}, group['id'])
}
If it is returning an SSL error like:
/lib/ruby/2.0.0/net/http.rb:918:in `connect': SSL_connect returned=1 errno=0 state=SSLv3 
read server certificate B: certificate verify failed (Faraday::SSLError)
Then you need to download the cacert.pem file from http://curl.haxx.se/ca/cacert.pem. 
Save the file to C:\RailsInstaller\cacert.pem and add it to your system as system variable:
SSL_CERT_FILE=C:\RailsInstaller\cacert.pem 



		                		
Tagged , , ,

Ruby Gravatar Link generator

Just a simple example of Ruby code to generate a gravatar link, substitute the xxxx@gmail.com with the desired address and you will get the something like:

http://www.gravatar.com/avatar/d02770a3574d9ed0ee364c49d5fb14d3?

In the second use case you can specify the size of the gravatar, the default image in case no gravatar is found and the rating:

http://www.gravatar.com/avatar/d02770a3574d9ed0ee364c49d5fb14d3?size=200&default=https%3A%2F%2Fimage-not-found-link.jpg&rating=pg

 

#!/usr/bin/env ruby
require 'digest/md5'
require 'uri'
 
# this is based on gravatar image API
# https://en.gravatar.com/site/implement/images/
# options :
# size : <integer> size of image
# default: <string> url of image if email not found or:
# * 404
# * mm
# * identicon
# * monsterid
# * wavatar
# * retro
# * blank
# forcedefault: "y" force default image to load
# rating: <string> one of the values : g, pg, r, x
def gravatar email, options={}
  email_md5 = Digest::MD5.hexdigest email
  params_query = URI.encode_www_form(options) unless options.empty?
  "http://www.gravatar.com/avatar/#{email_md5}?#{params_query}"
end
 
 
puts gravatar('xxxx@gmail.com')
puts gravatar('xxxx@gmail.com',
              size: 200,
              default: '404',
              rating: 'pg'
     )
Tagged , ,

Setup Rails development environment on Windows 7 machine

Today I decided to go back to one of my previous interests and start to build a Rails application. I already set up my machine in the past, but since then I formatted it at least three times and I scare nothing left from this setup.

So I decided to have a look at the official guide online, you can find good information on http://rubyonrails.org/, a very useful portal with most of the information you need.

If you click on the “get started” icon you will forwarded to the download page which contains the steps to reach a fully working development environment.

First step:

rubyInstall Ruby (Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. from Wikipedia.org) which is the core of Rails and makes everything possible. I installed the version Ruby 1.9.3 using the windows installer rubyinstaller-1.9.3-p0.exe.

Second step:

rubygemsThe official guide says that we have to install RubyGem, the standard Ruby package manager, but it was already present on my system after the Ruby installation. Anyway if you want to install it by hand just download it from RubyForge: rubygems-1.8.15.zip. After the installation update the currently gems by running:

  gem update --system

and then:

 gem install rubygems-update
 update_rubygems

Third step:

Thru RubyGem you can easily install all the gems via cmdline just running:

gem install package

in that case it should be:

gem install rails

And all the dependencies and the related gems will be installed automagically. RubyGem rocks.

Now everything is in place to start building your new Rails application. I personally suggest RadRails as eclipse plugin (there is also a standalone IDE) as development IDE.

EDIT:

Do not forget to install the DevKit, otherwise you will not be able to start your application, since some gem will be missing. The latest DevKit can be found here: http://rubyinstaller.org/downloads/

Tagged , , , ,