Created
March 29, 2011 11:56
-
-
Save yuya-takeyama/892221 to your computer and use it in GitHub Desktop.
DSL to write .htaccess files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.htaccess ファイルを DSL で記述するってどうでしょう ? | |
使い方: | |
$ ruby build_htaccess.rb example.rb | |
出力: | |
<IfModule mod_rewrite.c> | |
RewriteEngine on | |
<Limit GET> | |
RewriteRule ^/user/(.*)$ /user.cgi?id=$1 [L,R] | |
</Limit> | |
</IfModule> | |
Order Deny,Allow | |
Deny from All | |
Allow from 192.168.0.11 | |
Allow from 192.168.0.12 | |
Allow from 192.168.0.13 | |
Allow from 192.168.0.14 | |
Allow from 192.168.0.15 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './htaccess_dsl' | |
include HtaccessDsl | |
load ARGV[0] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dsl { | |
IfModule("mod_rewrite.c") { | |
RewriteEngine :on | |
Limit("GET") { | |
RewriteRule "^/user/(.*)$ /user.cgi?id=$1 [L,R]" | |
} | |
} | |
Order "Deny,Allow" | |
Deny "from All" | |
(11..15).each do |n| | |
Allow "from 192.168.0.#{n.to_s}" | |
end | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HtaccessDsl | |
class Htaccess | |
def initialize | |
@lines = [] | |
@depth = 0 | |
end | |
def method_missing(method, *args, &block) | |
if block_given? | |
_put_block(method, *args, &block) | |
else | |
_puts(method.to_s + " " + args[0].to_s) | |
end | |
end | |
# ディレクティブの指定 | |
def _puts(line) | |
@lines << _indent + line | |
end | |
# ブロック形式の記述 | |
def _put_block(directive, cond = nil, &block) | |
if cond.nil? | |
@lines << _indent + "<#{directive.to_s}>" | |
else | |
@lines << _indent + "<#{directive.to_s} #{cond}>" | |
end | |
@depth += 1 | |
instance_eval(&block) | |
@depth -= 1 | |
@lines << _indent + "</#{directive.to_s}>" | |
end | |
# インデント | |
def _indent | |
" " * @depth | |
end | |
# 出力 | |
def _output | |
@lines.each do |line| | |
puts line | |
end | |
end | |
end | |
# 渡されたブロックを DSL として解釈し, .htaccess 形式に出力 | |
def dsl(&block) | |
htaccess = Htaccess.new | |
htaccess.instance_eval(&block) | |
htaccess._output | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment