初回表示用のレイアウトが定義されていて
app/controllers/my_controller.rb
DEFAULT_LAYOUT = { 'left' => ['issuesassignedtome'],
'right' => ['issuesreportedbyme']
}.freeze
表示する時にユーザが未設定の状態の時は、初回表示用のレイアウトを表示するようにしている。
app/controllers/my_controller.rb
def index
page
render :action => 'page'
end
# Show user's page
def page
@user = User.current
@blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT # <- 初回表示用のレイアウトを渡している
end
追加する時にユーザが未設定の状態の時は、空のレイアウトを読み込み、追加しているのでレイアウトがリセットされる。
app/controllers/my_controller.rb
# Add a block to user's page
# The block is added on top of the page
# params[:block] : id of the block to add
def add_block
block = params[:block].to_s.underscore
if block.present? && BLOCKS.key?(block)
@user = User.current
layout = @user.pref[:my_page_layout] || {} # <- 空のレイアウトを渡している
# remove if already present in a group
%w(top left right).each {|f| (layout[f] ||= []).delete block }
# add it on top
layout['top'].unshift block
@user.pref[:my_page_layout] = layout
@user.pref.save
end
redirect_to my_page_layout_path
end
リセットされるのは良いけど、いきなり消えてしまうのでもう少し見せ方を工夫する余地がありそう。