27 Jan How to execute shell commands using ruby in a rake task
In the past days I attended the http://gophergala.com/ event which it was a really good start in the Golang world, I learned some stuff about Golang, after to read this previous sentences you are going to say WTF is this post about ruby or Golang well I wanted to start writting about the Gophergala because the code that we are going create is created with the aim and purpose of cloning all the repositories from an account in this case the gophergala organization using ruby in a rake task, Why Am I doing this? just to put in only one place all these great resources (I will put in my account all of this repositories in one repository).
We need to create our Gemfile with the code bellow:
source 'http://rubygems.org' gem 'httparty' gem 'pry' gem 'rake'
Then we have to run the command:
bundle install
I have created a class to retrieve all the repositories name using the github api, this is how it looks my github_downloader.rb file:
require 'httparty' class GithubDownloader def self.get_all_repositories page = 0 repo_array = [] loop do page+=1 url = "https://api.github.com/orgs/gophergala/repos?page=#{page}&per_page=100" repositories = HTTParty.get(url) repositories.each do |repo| repo_array << repo['clone_url'] end break if repositories.empty? end return repo_array end end
Now let’s create our Rakefile file with the following code:
require './github_downloader' require 'pry' namespace :downloader do desc "Print a hello world message" task :gopher_gala_repositories do repositories = GithubDownloader.get_all_repositories repositories.each do |repo_name| sh "cd ~/Home/my_directory; git clone #{repo_name}" end end end
In the previous code I’m cloning all the repositories inside my_directory folder as simple as that.
Well this is most useful in the code in the world that’s why I’m writting it, LOL.
BTW if you want to find all the resources and repositories created during the Gophergala this is what you are looking for: https://github.com/heridev/gophergala_repositories
H.
No Comments