Halaman

Tampilkan postingan dengan label ruby. Tampilkan semua postingan
Tampilkan postingan dengan label ruby. Tampilkan semua postingan

Jumat, 11 April 2014

Rails (Rack::Utils) HTTP Status Codes and Symbols

ruby -e 'require "rack/utils"; puts Rack::Utils::SYMBOL_TO_STATUS_CODE.map{|s,c| "|" + c.to_s.center(5) + "|" + s.inspect.center(60) + "|" + Rack::Utils::HTTP_STATUS_CODES[c].to_s.center(60) + "|"}.join("\n")'
| 100 |                         :continue                          |                          Continue                          |
| 101 |                    :switching_protocols                    |                    Switching Protocols                     |
| 102 |                        :processing                         |                         Processing                         |
| 200 |                            :ok                             |                             OK                             |
| 201 |                          :created                          |                          Created                           |
| 202 |                         :accepted                          |                          Accepted                          |
| 203 |               :non_authoritative_information               |               Non-Authoritative Information                |
| 204 |                        :no_content                         |                         No Content                         |
| 205 |                       :reset_content                       |                       Reset Content                        |
| 206 |                      :partial_content                      |                      Partial Content                       |
| 207 |                       :multi_status                        |                        Multi-Status                        |
| 208 |                     :already_reported                      |                      Already Reported                      |
| 226 |                          :im_used                          |                          IM Used                           |
| 300 |                     :multiple_choices                      |                      Multiple Choices                      |
| 301 |                     :moved_permanently                     |                     Moved Permanently                      |
| 302 |                           :found                           |                           Found                            |
| 303 |                         :see_other                         |                         See Other                          |
| 304 |                       :not_modified                        |                        Not Modified                        |
| 305 |                         :use_proxy                         |                         Use Proxy                          |
| 306 |                         :reserved                          |                          Reserved                          |
| 307 |                    :temporary_redirect                     |                     Temporary Redirect                     |
| 308 |                    :permanent_redirect                     |                     Permanent Redirect                     |
| 400 |                        :bad_request                        |                        Bad Request                         |
| 401 |                       :unauthorized                        |                        Unauthorized                        |
| 402 |                     :payment_required                      |                      Payment Required                      |
| 403 |                         :forbidden                         |                         Forbidden                          |
| 404 |                         :not_found                         |                         Not Found                          |
| 405 |                    :method_not_allowed                     |                     Method Not Allowed                     |
| 406 |                      :not_acceptable                       |                       Not Acceptable                       |
| 407 |               :proxy_authentication_required               |               Proxy Authentication Required                |
| 408 |                      :request_timeout                      |                      Request Timeout                       |
| 409 |                         :conflict                          |                          Conflict                          |
| 410 |                           :gone                            |                            Gone                            |
| 411 |                      :length_required                      |                      Length Required                       |
| 412 |                    :precondition_failed                    |                    Precondition Failed                     |
| 413 |                 :request_entity_too_large                  |                  Request Entity Too Large                  |
| 414 |                   :request_uri_too_long                    |                    Request-URI Too Long                    |
| 415 |                  :unsupported_media_type                   |                   Unsupported Media Type                   |
| 416 |              :requested_range_not_satisfiable              |              Requested Range Not Satisfiable               |
| 417 |                    :expectation_failed                     |                     Expectation Failed                     |
| 422 |                   :unprocessable_entity                    |                    Unprocessable Entity                    |
| 423 |                          :locked                           |                           Locked                           |
| 424 |                     :failed_dependency                     |                     Failed Dependency                      |
| 425 | :reserved_for_webdav_advanced_collections_expired_proposal | Reserved for WebDAV advanced collections expired proposal  |
| 426 |                     :upgrade_required                      |                      Upgrade Required                      |
| 509 |                        :unassigned                         |                         Unassigned                         |
| 428 |                   :precondition_required                   |                   Precondition Required                    |
| 429 |                     :too_many_requests                     |                     Too Many Requests                      |
| 431 |              :request_header_fields_too_large              |              Request Header Fields Too Large               |
| 500 |                   :internal_server_error                   |                   Internal Server Error                    |
| 501 |                      :not_implemented                      |                      Not Implemented                       |
| 502 |                        :bad_gateway                        |                        Bad Gateway                         |
| 503 |                    :service_unavailable                    |                    Service Unavailable                     |
| 504 |                      :gateway_timeout                      |                      Gateway Timeout                       |
| 505 |                :http_version_not_supported                 |                 HTTP Version Not Supported                 |
| 506 |         :"variant_also_negotiates_(experimental)"          |           Variant Also Negotiates (Experimental)           |
| 507 |                   :insufficient_storage                    |                    Insufficient Storage                    |
| 508 |                       :loop_detected                       |                       Loop Detected                        |
| 510 |                       :not_extended                        |                        Not Extended                        |
| 511 |              :network_authentication_required              |              Network Authentication Required               |

Sabtu, 06 Juli 2013

Sharing gems (or any files really) from lubuntu to windows

Continuing from my previous post about developing rails using lubuntu vm as rails server, I need to have access to gem files inside lubuntu from windows for viewing its sources..

At first I tried to use virtual box shared folders to store rbenv/gems files but it cause many problems in ruby or at the very least it result in a very slow performance (especially when gems are loading)

After many many sleepless nights (dramatization) I finally succeed by using samba and sharing the gems via (virtual) network with the following steps..

Jumat, 28 Juni 2013

Developing Rails in Windows using Linux Server



Developing rails/ruby app in windows is painful as many gems aren't compatible or optimized for windows. But windows is OS that I'm most comfortable with.. Linux (ubuntu) lack some tools that I need and I simply hate OSX (stupid keyboard layout and hardware restriction), so I prefer dealing with gem problems rather than changing OS..

But then it occurred to me, why not just use virtual machine with linux for server? And turns out it's pretty neat.. And I think some people are too use windows as main OS so I posted here the step for setting up linux vm for rails..

Selasa, 18 September 2012

tcs-ruby: faster ruby for windows

As a rails developer using windows as my development machine I often getting annoyed on how much time needed to start things especially tests.
In case you're wondering why did I use windows instead of other OS-es better suited for ruby like MacOSX/linux it's because I'm comfortable with it and if you're disagree then feel free to stop reading at this point :)

Several days ago I found about this fork of ruby by TheCodeShop which will speed up things quiet significantly, I decided to try it and one of my project unit tests which needed around 45 sec to complete reduced to less than 20 sec.

Installation


This step assume you're using Win7 with pik to manage multiple ruby installation, if you don't have pik yet get it from https://github.com/vertiginous/pik

  1. Download one of ruby build from:
    https://github.com/thecodeshop/ruby/wiki/Downloads
    (I'm using winio one)
  2. Extract it, for example to C:\Ruby-tcs193
  3. Modify Path to use ruby-tcs: go to Control Panel, System, Advanced System Settings, Environment Variables
  4. Edit Path in User variables, modify existing Ruby bin path to ruby-tcs bin (C:\Ruby-tcs193)
  5. Add new variable RUBYOPT with value: "-rfenix/replace"
  6. Next, add it to pik (you can stop here if you didn't use pik, but I recommend it in case you need to switch to standard ruby)
  7. open cmd, then enter "pik add [path to ruby-tcs bin]" for example "pik add C:\Ruby-tcs193\bin"
  8. Lastly install devkit for it, run "ruby c:\devkit\dk.rb init" then "ruby c:\devkit\dk.rb install"
  9. Done :)


Known problems


Heroku commands

heroku commands will raise error because of non existing fenix/replace, to fix simply remove RUBYOPT temporarily by entering "set RUBYOPT="

Standard ruby

same as above because standard ruby didn't use fenix so remove RUBYOPT temporarily

Sabtu, 31 Desember 2011

ubuntu 11.10 rails 3 passenger

http://ubuntuandrails.blogspot.com/2011/11/installing-rails-311-ruby-193-apache2.html

Senin, 03 Oktober 2011

install mysql2 > 0.3.6 for mysql 64bit in windows

gem install mysql2 --platform=ruby -- '--with-mysql-lib="C:\Program Files\MySQL\MySQL Server 5.5\lib" --with-mysql-include="C:\Program Files\MySQL\MySQL Server 5.5\include"'

http://dev.mysql.com/downloads/connector/c/

copy  C:\mysql-connector-c-noinstall-6.0.2-win32\lib\libmysql.dll to ruby\bin

original source: http://blog.mmediasys.com/2011/07/07/installing-mysql-on-windows-7-x64-and-using-ruby-with-it/

Kamis, 30 Juni 2011

Additional Range method

class Range
  # return true if 2 range overlapped
  def overlap? other_range
    include?(other_range.begin) || other_range.include?(self.begin)
  end

  # return a new intersection range between two ranges
  def & other_range
    raise TypeError, "exclusive range can't be intersected with non-exclusive one" unless self.exclude_end? == other_range.exclude_end?
    new_begin = [self.begin, other_range.begin].max
    new_end = [self.end, other_range.end].min
    new_begin <= new_end ? Range.new(new_begin, new_end, self.exclude_end?) : nil
  end

  # return true if other_range is a subset in self
  def contains? other_range
    if !exclude_end?
      include?(other_range.begin) && include?(other_range.end)
    elsif self.begin.respond_to?('>=')
      self.begin <= other_range.begin && self.end.send(other_range.exclude_end? ? '>=' : '>', other_range.end)
    else
      raise TypeError, "can't determine inclusion of range with this type of members"
    end
  end

  # return true if self is a subset of other_range
  def within? other_range
    other_range.contains? self
  end

  # return length of the range (only for subtract-able range)
  def length
    self.end.respond_to?('-') ? self.end - self.begin : nil
  end

  # return next range with same span (only for subtract-able and add-able range)
  def succ allow_touch=false
    return nil unless self.end.respond_to?('-') && self.end.respond_to?('+')
    new_begin = allow_touch || exclude_end? || !self.end.respond_to?(:succ) ? self.end : self.end.succ
    new_end = new_begin + length
    Range.new(new_begin, new_end, exclude_end?)
  end

  # return previous range with same span (only for subtract-able and add-able range)
  def pred allow_touch=false
    return nil unless self.end.respond_to?('-') && self.begin.respond_to?('+')
    new_end = allow_touch || exclude_end? || !self.begin.respond_to?(:pred) ? self.begin : self.begin.pred
    new_begin = new_end - length
    Range.new(new_begin, new_end, exclude_end?)
  end
end

Selasa, 28 Juni 2011

array flatten with level for ruby 1.8.7

straight to the code:
class Array
  alias_method :orig_flatten, :flatten
  
  def flatten level=nil
    if level.is_a?(Integer)
      temp_arr = clone
      level.times{ |i| temp_arr = temp_arr.inject([]){|s,v| v.is_a?(Array) ? s.concat(v) : s << v} }
      temp_arr
    else
      orig_flatten
    end
  end
end

of course although untested i'm sure it will have worse performance than the original flatten in ruby 1.9.2, but better than nothing right? ;)

ruby array to hash method

update 2012-12-21:
you should use flat_map instead of flatten, i'm too lazy to update the code though.. :P

we can convert hash to array easily using .to_a method for example:
hsh = {:a => 1, :b => 2, :c => 3}
arr = hsh.to_a # -> [[:a, 1], [:b, 2], [:c, 3]]

but there's no built in method to reverse that, there's no .to_hash instance method for array.

to solve that i added a simple instance method for array:
class Array
  def to_hash values=nil
    Hash[*(values.is_a?(Array) ? self.zip(values) : self).flatten(1)]
  end
end

hsh = {:a => 1, :b => 2, :c => 3}
arr = hsh.to_a # -> [[:a, 1], [:b, 2], [:c, 3]]
arr.to_hash == hsh # -> true
[:a,:b,:c].to_hash [1,2,3] # -> {:a => 1, :b => 2, :c => 3}

a little precaution, flatten(1) will not work properly in ruby 1.8.7 or older, therefore it won't be possible to create hash with array as key or value. but there's a simple workaround for that by overriding array flatten method to behave like ruby 1.9.2 in my next post :)

useful online tools for web programming

  • Regex for ruby: http://www.rubular.com/
  • strftime: http://strfti.me/
  • css gradient generator: http://www.colorzilla.com/gradient-editor/
  • css validator: http://jigsaw.w3.org/css-validator/
  • css rounder corner generator: http://a.deveria.com/roundgen/
  • 7 great js resources (not really a tool but useful): http://mashable.com/2011/07/03/7-great-javascript-resources

will be updated as i found another tools

Rabu, 01 Juni 2011

Counting sub-string occurrence in a string

Once upon a time.. I need a way to count number of occurrence of certain sub-string (not exclusively words) inside a string.

For example, string "Aya Hirano is the best seiyuu in the world! She was mostly known as her role as Haruhi." I wanted to know how many times string "he" occurred in there.
The result should be 4, 2 in the, 1 in She and 1 in her.

By using scan method we can do that easily:
class String
  def substr_count(pattern)
    self.scan(pattern).length
  end
end

"Aya Hirano is the best seiyuu in the world! She was mostly known as her role as Haruhi.".substr_count("he") # -> 4
"Aya Hirano is the best seiyuu in the world! She was mostly known as her role as Haruhi.".substr_count(/(!|\.|\?)/) # -> 2 -> counting sentences? :D

Too simple to become share-worthy article I guess.. :P

Rabu, 22 September 2010

ruby installer development kit

a note to self for devkit problem

error:

"Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers."

or

"You have to install development tools first."

see:
http://github.com/oneclick/rubyinstaller/wiki/development-kit