Tuesday, July 27, 2010

Posterous

Posterousというブログサービスを試してみる
投稿はメールですることが基本になっていて
最初の投稿はアカウントを取る前にできてしまう
ソーシャル的な要素が強くて
ブログとTwitterを合わせたような感じ
他者のブログをfollower登録みたいにそこで購読できる

Friday, July 23, 2010

conv.rb

to_s(base), to_i(base)を94まで対応

#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
module Conv
  TABLE = ('!'..'~').to_a

  def to_s_conv(base, rs=[])
   q, r = self.divmod base
   rs.unshift TABLE[r]
   q.to_s_conv(base, rs) if q > 0
   rs.join
  end

  def to_i_conv(base)
    self.split(//).reverse.map.with_index { |s, i| TABLE.index(s).to_i * base**i }.inject(:+)
  end
end

class Fixnum
  include Conv
  alias to_s_orig to_s
  def to_s(base=10)
    base > 36 ? to_s_conv(base) : to_s_orig(base)
  end
end

class Bignum
  include Conv
  alias to_s_orig to_s
  def to_s(base=10)
    base > 36 ? to_s_conv(base) : to_s_orig(base)
  end
end

class String
  include Conv
  alias to_i_orig to_i
  def to_i(base=10)
    base > 36 ? to_i_conv(base) : to_i_orig(base)
  end
end

x = 200_000_000_000
(2..94).each do |i|
  s = x.to_s(i)
  print "#{i} => #{s}:#{s.to_i(i)}\n"
end


 

Thursday, July 22, 2010

TinyURL with Ruby

Points
  • urlをDBのidに置き換え、さらにInteger#to_i(36)を使って短縮する
  • cssをw3cサイトから借用
  • 環境変数envから参照元つまり自サイトのurlを取得

 
%w(rubygems sinatra dm-core dm-timestamps dm-migrations uri).each { |lib| require lib }

configure :development do
  DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/chop.db")
end

get '/' do
  haml :index
end

post '/' do
  uri = URI::parse(params[:original])
  raise "Invalid URL" unless [URI::HTTP, URI::HTTPS].any? { |scm| uri.kind_of? scm }
  @url = Url.first_or_create(:original => uri.to_s)
  haml :index
end

get '/:chopped' do |chopped|
  redirect Url.first(:id => chopped.to_i(36)).original
end

error do
  'Sorry there was a nasty error - ' + env['sinatra.error'].name
end

class Url
  include DataMapper::Resource
  property :id,         Serial
  property :original,   String, :length => 255
  property :created_at, DateTime

  def chopped
    self.id.to_s(36)
  end
end

__END__
@@ layout
!!! 1.1
%html
  %head
    %title Chop!
    %link{:rel => 'stylesheet', :href => 'http://www.w3.org/StyleSheets/Core/Modernist', :type => 'text/css'}
  %body
    = yield

@@ index
%h1.title Chop!
- unless @url.nil?
  %code= @url.original
  chopped to
  %a{:href => env['HTTP_REFERER'] + @url.chopped}
    = env['HTTP_REFERER'] + @url.chopped
%form{:method => 'post', :action => '/'}
  Chop this:
  %input{:type => 'text', :name => 'original', :size => '50'}
  %input{:type => 'submit', :value => 'chop!'}
%small copyright ©


Friday, July 09, 2010

denki

電気代
2010年7月分
6,759円(295kW)

2008年が6069円