以前我们这样使用TimeZone:
[code]
class TasksController < ApplicationController
def create
task = account.tasks.build(params[:task])
task.alert_at = current_user.time_zone.local_to_utc(task.alert_at)
task.save!
end
end
[/code]
每次我们需要使用时区转换时我们都要写类似[b]task.alert_at = current_user.time_zone.local_to_utc(task.alert_at)[/b]的语句
我们可以试试tztime插件,它将set_timezone的逻辑脱离出来:
[code]
class ApplicationController < ActionController::Base
around_filter :set_timezone
private
def set_timezone
TzTime.zone = current_user.time_zone
yield
TzTime.reset!
end
end
class Task < ActiveRecord::Base
tz_time_attributes :alert_at
end
class TasksController < ApplicationController
def create
task = account.tasks.create(params[:task])
end
end
[/code]
这样我们不用每次都调用set_timezone,我们用tz_time_attributes来声明哪些属性使用TzTime即可
[code]
class TasksController < ApplicationController
def create
task = account.tasks.build(params[:task])
task.alert_at = current_user.time_zone.local_to_utc(task.alert_at)
task.save!
end
end
[/code]
每次我们需要使用时区转换时我们都要写类似[b]task.alert_at = current_user.time_zone.local_to_utc(task.alert_at)[/b]的语句
我们可以试试tztime插件,它将set_timezone的逻辑脱离出来:
[code]
class ApplicationController < ActionController::Base
around_filter :set_timezone
private
def set_timezone
TzTime.zone = current_user.time_zone
yield
TzTime.reset!
end
end
class Task < ActiveRecord::Base
tz_time_attributes :alert_at
end
class TasksController < ApplicationController
def create
task = account.tasks.create(params[:task])
end
end
[/code]
这样我们不用每次都调用set_timezone,我们用tz_time_attributes来声明哪些属性使用TzTime即可
本文介绍了一种简化Rails应用中时区处理的方法。通过使用TzTime插件,可以避免每次手动进行时区转换,只需在模型中声明使用TzTime的属性即可自动完成转换。
764

被折叠的 条评论
为什么被折叠?



